Removing modules from the global namespace

Chris Jaeger cjaeger at ensim.com
Mon May 14 17:30:27 EDT 2001


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.

Thanks,
Chris


Bjorn Pettersen wrote:
> 
> > From: Chris Jaeger [mailto:cjaeger at ensim.com]
> >
> > Hi all,
> >
> >       I was wondering if there was a way to remove
> > imported modules from a namespace. For instance, I
> > have an __init__.py that loads a dynamic list of modules
> > based on what it finds present in the directory. In order
> > to determine the contents of the directory, I need to import
> > os, string, etc. Before I return from __init__.py, I'd like
> > to remove all the modules from the namespace for this package
> > except for the ones that come from this directory. Can this
> > be done?
> 
> Can't you just put your functionality in a function, and import the modules
> inside the function instead of at the global level?
> 
> -- bjorn




More information about the Python-list mailing list