import module from package - confusing syntax

David MacQuigg dmq at gain.com
Sun Jul 4 08:49:34 EDT 2004


On Sat, 03 Jul 2004 08:54:50 -0500, Mark McEahern
<marklists at mceahern.com> wrote:

>On Sat, 2004-07-03 at 08:21, David MacQuigg wrote:
>> I'm setting up a large hierarchy of module packages and using a
>> variable to select which of many alternative packages to import.
>
>This means you need __import__.

__import__ looks even messier than exec()  We have to interpolate the
string 'config.modsel' twice.

import libs, config
config.modsel = 'modsel01'

##    # What we want:
##    from (config.modsel).modelselector import ModelSelector

##    # Works, but messy:
##    __import__('libs.%s.modelselector' % config.modsel)
##    modsel = getattr(libs, config.modsel)
##    ModelSelector = modsel.modelselector.ModelSelector

# Still seems like the lesser evil:
exec('from libs.%s.modelselector import ModelSelector' %
     config.modsel)

The __import__ function looks like a real kludge.  There is a
suggestion in section 2.1 of the Library Reference to use the 'imp'
module, and write my own import function.  I guess I'll look at that
next.

-- Dave




More information about the Python-list mailing list