En Mon, 05 Nov 2007 10:34:26 -0300, Frank Aune <[EMAIL PROTECTED]>  
escribió:

> I have a python library package 'Foo', which contains alot of submodules:
>
> Foo/:
>       __init__.py
>       module1.py:
>               class Bar()
>               class Hmm()
>       module2.py
>               class Bee()
>               class Wax()
>       module3.py
>               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 __init__.py:
>
> 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  
Foo/__init__.py:

<code>
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())

import_all_modules()
del import_all_modules
</code>

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to