on package import, have it conditionally import a subpackage
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Sep 21 23:36:18 EDT 2009
En Sat, 19 Sep 2009 17:06:11 -0300, Gabriel Rossetti
<gabriel.rossetti at arimaz.com> escribió:
> 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.
That depends on how dynamic you want/have to be.
(inside mybase/mypkg.__init__py):
def setType(type_):
global module1, module2
if type_ == 'type1':
from .type1 import module1, module2
elif type_ == 'type2':
from .type2 import module1, module2
else:
raise ValueError, 'unknown type: %s' % type_
A more generic version:
def setType(type_):
global module1, module2
t = __import__(type_, globals(), locals(), ['module1','module2'], 1)
module1 = t.module1
module2 = t.module2
--
Gabriel Genellina
More information about the Python-list
mailing list