How to make a conditional import???

Thomas Wouters thomas at xs4all.net
Fri Nov 10 13:05:26 EST 2000


On Fri, Nov 10, 2000 at 03:09:55PM +0100, Peter Arwanitis wrote:

> I'm ever trapped by 'import'-problems :)

Well, in this case, you're trapped by 'from ... import *'. Don't do that.
Really, you don't want to use 'from .. import *'. It has very specific uses,
and none apply in this case, I think ;)

> from string import *

> def selectProjectType():
>     #...    skipped
>     if projectType == 'phys':
>         from pyhsModule import *
>     else:
>         from logicModule import *

> everybody know the effect... the import statement in selectProjectType() is
> only processed locally!

Yes. This part of Python is *slightly* different in Python 1.5.2 and Python
2.0. In 1.5.2, 'from ... import <symbols>' is always local, both in the
'name, name, name' form and in the '*' form. In Python 2.0, you can use the
'global' directive on symbols listed in 'from ... import ...', but not on
symbols imported by 'from .. import *' -- yet another reason not to use
'from ... import *' !

> But I need it global, like the string import...

> PLEASE: I need a quick solution, and not a code-philosophy-thread :-)
> I know, that I can make it better on other ways (and without from...)
> BUT is there a obfuscated solution to make this import happen in global
> scope???

If you use Python 2.0, you might get what you want by using 'global' mixed
with naming the symbols you want to import:

def selectProjectType():
    global spam, eggs, ham
    if projectType == 'phys':
	from physModule import spam, eggs, ham
    else:
	from logicModule import spam, eggs, ham

This does not work in Python 1.5.2, however. For 1.5.2, you *can* use
something like this:

import physModule, logicModule

def selectProjectType():
    global spam, eggs, ham
    if projectType == 'phys':
	spam, eggs, ham = physModule.spam, physModule.eggs, physModule.ham
    else:
	spam, eggs, ham = logicModule.spam, logicModule.eggs, logicModule.ham

(or you can do the actual import in the 'if' blocks, if you wish.)

Of course, if you want *really* obfuscated, won't have to debug the code,
won't have to reread the code, and won't actually *use* the code, you can
take the quick shortcut of 'exec "from %s import *"%projectType in globals()'.
That's even worse than using 'from string import *' though ;-)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list