import module from package - confusing syntax

David MacQuigg dmq at
Sat Jul 3 15:21:05 CEST 2004

I'm setting up a large hierarchy of module packages and using a
variable to select which of many alternative packages to import.  For
example, the variable 'config.modsel' points to a particular "model
selector" package.  'config' is a module containing many such

My first attempt resulted in a confusing error message:

>>> from config.modsel.modelselector import ModelSelector

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in -toplevel-
    from config.modsel.modelselector import ModelSelector
ImportError: No module named modsel.modelselector

It works if I enter the literal path rather than a variable:

>>> config.modsel
<module 'libs.modsel01' ... >
>>> from libs.modsel01.modelselector import ModelSelector
>>> ModelSelector
<class libs.modsel01.modelselector.ModelSelector at 0x009F68D0>

I need to use a variable, however.  The best I can come up with is:

>>> exec('from '+ config.modsel.__name__ +'.modelselector import ModelSelector')

Is this the best we can do with current Python syntax?

Should we think about suggesting a better syntax?  I think the
fundamental problem is the confusion that arises from using '.' as
both a path separator and an attribute qualifier.

-- Dave

More information about the Python-list mailing list