Modules are Singletons! (was Re: Catalog of Python Patterns? [LONG!])
Alexandre Fayolle
alf at logilab.fr
Mon Apr 8 08:16:46 EDT 2002
Gustavo Cordova wrote:
>
> Andy hadn't caught on that a module is loaded only once,
> the first time it's imported. Any subsequent imports are
> only accesses to the original imported version, so that
> makes them effectively singletons.
Stop me if I'm wrong, but this is actually not quite true.
Suppose you have a package called 'p' containing modules
m1 and m2. You also have another module called 'n' somewhere
else. m2 is your wanabe singleton, and has a function
called 'foo'.
In m1, you can access m2 with a simple 'from m2 import foo',
but in n, you have to 'from p.m2 import foo'. In this case,
m2 is imported twice, and changes to global variables are not
made.
The solution is to use 'from p1.m2 import foo' in module m1.
Alexandre Fayolle
--
LOGILAB, Paris (France).
http://www.logilab.com http://www.logilab.fr http://www.logilab.org
Narval, the first software agent available as free software (GPL).
More information about the Python-list
mailing list