Removing modules from the global namespace

Bjorn Pettersen BPettersen at
Mon May 14 17:53:22 EDT 2001

> From: Chris Jaeger [mailto:cjaeger at]
> Hi Bjorn,
> 	Forgive me if this should be obvious; this is
> my first real exposure to python. 
> 	I have a python program that I want to import
> a number of modules into, but I don't know what the
> set of modules are going to be until run-time. Each
> loadable module exports an identical API. My layout
> currently is:
> modules
>  \_
>  \_
>  \_	
>  \_ ...
>  \_
> imports modules, uses dir(modules)
> to get the list of names of imported modules, and then
> cycles though each module calling some function.
> Is there a better idiom to handle this than the one
> I am using? I would rather not modify modules/
> every time a new module is placed in the modules directory.

Sorry for not explaining well enough. I was thinking about something along
these lines (

def findModules():
    # these imports are local to this function
    import os
    import re
    import string
    res = []
    local_dir = os.path.dirname(__file__)
    entries = os.listdir(local_dir)
    for entry in entries:
	if re.match(r"*.\.py$",entry) or re.match(r"*.\.pyc",entry):
		module = string.join(string.split(entry,'.')[:-1],'.')
		if module != "__init__":
    return res
for module in findModules():
    __import__(module, globals(), locals(), [])

-- bjorn

More information about the Python-list mailing list