relative imports with the __import__ function

Chris Colbert sccolbert at gmail.com
Tue Dec 8 10:10:45 EST 2009


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.

In the following code segment, the failing code is uncommented, but
the commented code works fine:

seg_mod = 'red_objects'
smod = __import__('..segmentation.%s' % seg_mod, fromlist=[seg_func], level=-1)

#from ..segmentation import red_objects
#smod = red_objects

I have tried all sorts of values for the 'level' kwarg as well as
everywhich variation of the dotted relative notation.

I'm assuming i'm missing something fundamental on the import resolution...

As an aside, I would like to move main.py inside of the package
directory, but I dont know if that is possible with what i'm trying to
do here.

Thanks for any help.

Cheers!

Chris



More information about the Python-list mailing list