conditional import into global namespace

Diez B. Roggisch deets at nospam.web.de
Wed Mar 3 04:17:57 EST 2010


Am 02.03.10 21:41, schrieb mk:
> Jerry Hill wrote:
>> Just import subprocess at the top of your module. If subprocess
>> hasn't been imported yet, it will be imported when your module is
>> loaded. If it's already been imported, your module will use the
>> cached version that's already been imported.
>>
>> In other words, it sounds like Python already does what you want. You
>> don't need to do anything special.
>
> Oh, thanks!
>
> Hmm it's different than dealing with packages I guess -- IIRC, in
> packages only code in package's __init__.py was executed?

I don't understand this. But there is no difference regarding caching & 
execution between packages and modules.

Importing a package will execute the __init__.py, yes. But only once. As 
will importing modules execute them, but only once.

All subsequent imports will just return the created module-object. 
Unless you import something under a new name! That is, you can alter the 
sys.path and then import a package/module under a different name - 
python won't detect that.

Simplest example ist this:

---- test.py ----

class Foo(object):

    pass

if __name__ == "__main__":
    import test # import ourselves
    # this holds, because we have
    # __main__.Foo and test.Foo
    assert Foo is not test.Foo

---- test.py ----

However, unless you mess with python, this is none of your concern.

Diez



More information about the Python-list mailing list