Library package import question

Gabriel Genellina gagsl-py2 at
Tue Nov 6 01:37:03 CET 2007

En Mon, 05 Nov 2007 10:34:26 -0300, Frank Aune <Frank.Aune at>  

> I have a python library package 'Foo', which contains alot of submodules:
> Foo/:
> 		class Bar()
> 		class Hmm()
> 		class Bee()
> 		class Wax()
> 		etc etc
> To prevent namespace pollution, I want to import and use this library in  
> the
> following way:
> import Foo
> (...)
> t = Foo.module2.Bee()
> To accomplish this, I put explicit imports in
> import module1
> import module2
> import module3
> what Im wondering about, is if its a more refined way of doing this, as  
> the
> explicit imports now need to be manually maintained if the library grows.
> I've tried to use __all__, but this only seems to work with "from Foo  
> import
> *" and it causes modules to be imported directly into the namespace of
> course.

If I understand your question right, you want some way to automatically  
enumerate and import all *.py files inside your package. Try this inside  

def import_all_modules():
     "Import all modules in this directory"
     import os.path
     pkgdir = os.path.dirname(__file__)
     for filename in os.listdir(pkgdir):
         modname, ext = os.path.splitext(filename)
         if ext=='.py' and modname!='__init__':
             __import__(modname, globals())

del import_all_modules

Gabriel Genellina

More information about the Python-list mailing list