relative imports with the __import__ function
Peter Otten
__peter__ at web.de
Tue Dec 8 11:48:02 EST 2009
Chris Colbert wrote:
> I have package tree that looks like this:
>
> main.py
> package
> ----__init__.py
> ----configuration.ini
> ----server
> --------__init__.py
> --------xmlrpc_server.py
> --------controller.py
> --------reco
> ------------<irrelevant.py's>
> ----segmentation
> --------__init__.py
> --------red_objects.py
> ----<other irrelevant folders>
>
>
> main.py launches an instance of xmlrpc_server.py which, in turn,
> imports controller.py.
> controller.py reads configuration.ini to determine which
> module/function to import from the segmentation directory and
> subsequently use.
>
> that config file specifies the module as 'red_objects' and the
> function as 'segment_red'.
>
> I am trying to dynamically import that module and func using the
> __import__ statement but keep getting empty module errors.
> I'm assuming i'm missing something fundamental on the import resolution...
After some experimentation it turns out you have to provide some context for
__import__() to determine the absolute location of the requested module. The
required bit of information is the current module's __name__ attribute which
you can provide via the globals parameter:
def import_segmentation(name):
return getattr(__import__("segmentation." + name, level=2,
globals=globals()), name)
Peter
More information about the Python-list
mailing list