How to make a conditional import???

Alex Martelli aleaxit at
Fri Nov 10 17:04:59 CET 2000

"Peter Arwanitis" <arwanitis at> wrote in message
news:8ugvjf$25p$1 at
> def selectProjectType():
>     #...    skipped
>     if projectType == 'phys':
>         from pyhsModule import *
>     else:
>         from logicModule import *
> everybody know the effect... the import statement in selectProjectType()
> only processed locally!


> 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...)

Yeah, the from is the killer -- else, a simple 'global' for the
modulename you're importing should suffice.

> BUT is there a obfuscated solution to make this import happen in global
> scope???

It's not so much obfuscated as gross, but...:


    exec "from logicModule import *" in globals()

instead of

    from logicModule import *

should, I think, give you the effect you desire (*shudder*).

Or else, if you know you're in a module named 'silly'...:

    import silly
    import logicModule

I hope *this* one is sufficiently obfuscated for you...:-).

There are several variations possible on these (bad)
ideas, of course.


More information about the Python-list mailing list