on package import, have it conditionally import a subpackage

ryles rylesny at gmail.com
Sun Sep 20 17:18:36 EDT 2009


On Sep 19, 4:06 pm, Gabriel Rossetti <gabriel.rosse... at arimaz.com>
wrote:
> Hello everyone,
>
> I'd like to ba able to import a package and have it's __init__
> conditionally import a subpackage. Suppose that you have this structure :
>
> mybase/
> mybase/__init__.py
> mybase/mypkg
> mybase/mypkg/__init__.py
> mybase/mypkg/module0.py
> mybase/mypkg/type1
> mybase/mypkg/type1/__init__.py
> mybase/mypkg/type1/module1.py
> mybase/mypkg/type1/module2.py
> mybase/mypkg/type2
> mybase/ mypkg/type2/__init__.py
> mybase/ mypkg/type2/module1.py
> mybase/ mypkg/type2/module2.py
>
> I'd like to do something like th following in my code
>
>  >>> import mybase
>  >>> mybase.setType("type1")
>  >>> from mybase.mypkg import module0, module1, module2
>  >>> module0.__file__
> 'mybase/mypkg/module0.pyc'
>  >>> module1.__file__
> 'mybase/mypkg/type1/module1.pyc'
>  >>> module2.__file__
> 'mybase/mypkg/type1/module2.pyc'
>
> but I can't figure out how to do this.
>
> Thank you,
> Gabriel

You might try something like the following:

$ export PYTHONPATH=/home/ryles


$ cat mybase_test.py

import mybase

mybase.type = "type2"

from mybase.mypkg import module0, module1, module2

print module0.__file__
print module1.__file__
print module2.__file__


$ python mybase_test.py
/home/ryles/mybase/mypkg/module0.pyc
/home/ryles/mybase/mypkg/type2/module1.pyc
/home/ryles/mybase/mypkg/type2/module2.pyc


$ ls -l mybase/
-rw-r--r--  1 ryles None  44 Sep 20 16:59 __init__.py
drwxr-xr-x+ 4 ryles None   0 Sep 20 17:06 mypkg


$ cat mybase/__init__.py

default_type = "type1"

type = default_type


$ ls -l mybase/mypkg/
-rw-r--r--  1 ryles None 307 Sep 20 17:06 __init__.py
-rw-r--r--  1 ryles None   0 Sep 20 16:51 module0.py
drwxr-xr-x+ 2 ryles None   0 Sep 20 17:02 type1
drwxr-xr-x+ 2 ryles None   0 Sep 20 17:02 type2


$ ls -l mybase/mypkg/type1/
-rw-r--r-- 1 ryles None   0 Sep 20 16:49 __init__.py
-rw-r--r-- 1 ryles None   0 Sep 20 16:49 module1.py
-rw-r--r-- 1 ryles None   0 Sep 20 16:51 module2.py


$ ls -l mybase/mypkg/type2/
-rw-r--r-- 1 ryles None   0 Sep 20 16:48 __init__.py
-rw-r--r-- 1 ryles None   0 Sep 20 16:51 module1.py
-rw-r--r-- 1 ryles None   0 Sep 20 16:49 module2.py


$ cat mybase/mypkg/__init__.py

# These modules are hard-coded.
from mybase.mypkg import module0

# These modules are resolved dynamically.
from mybase import type
for module_name in ["module1", "module2"]:
    full_name = "mybase.mypkg." + type + '.' + module_name
    globals()[module_name] = __import__(full_name, {}, {},
[full_name])

$



More information about the Python-list mailing list