[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: conditional import into global namespace

mk

3/2/2010 8:42:00 PM

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?

Regards,
mk


1 Answer

Diez B. Roggisch

3/3/2010 9:18:00 AM

0

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