Removing modules from the global namespace

Bjorn Pettersen BPettersen at NAREX.com
Mon May 14 23:53:22 CEST 2001


> From: Chris Jaeger [mailto:cjaeger at ensim.com]
> 
> 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:
> 
> main.py
> modules
>  \_ __init__.py
>  \_ module1.py
>  \_ module2.py	
>  \_ ...
>  \_ moduleN.py
> 
> 	main.py 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/__init__.py
> 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 (__init__.py):

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__":
                res.append(module)
    return res
			
for module in findModules():
    __import__(module, globals(), locals(), [])

-- bjorn




More information about the Python-list mailing list