Modules are Singletons! (was Re: Catalog of Python Patterns? [LONG!])

Denis S. Otkidach ods at fep.ru
Mon Apr 8 08:47:56 EDT 2002


On Mon, 8 Apr 2002, Alexandre Fayolle wrote:

AF> Stop me if I'm wrong, but this is actually not quite true.
AF> Suppose you have a package called 'p' containing modules
AF> m1 and m2. You also have another module called 'n' somewhere
AF> else. m2 is your wanabe singleton, and has a function
AF> called 'foo'.
AF>
AF> In m1, you can access m2 with a simple 'from m2 import foo',
AF> but in n, you have to 'from p.m2 import foo'. In this case,
AF> m2 is imported twice, and changes to global variables are
AF> not
AF> made.

You are not right:

>>> import sys
>>> filter(lambda m: m.find('m1')>=0 or m.find('m2')>=0, sys.modules.keys())
[]
>>> from p import m1
>>> filter(lambda m: m.find('m1')>=0 or m.find('m2')>=0, sys.modules.keys())
['p.m1', 'p.m2']
>>> from p import m2
>>> filter(lambda m: m.find('m1')>=0 or m.find('m2')>=0, sys.modules.keys())
['p.m1', 'p.m2']






More information about the Python-list mailing list