surprising behaviour of global dictionaries

Peter Otten __peter__ at web.de
Tue Oct 9 11:24:18 EDT 2012


Michele Simionato wrote:

> I have the following module implementing a registry of functions with a
> decorator:
> 
> $ cat x.py
> registry = {} # global dictionary
> 
> def dec(func):
>     registry[func.__name__] = func
>     print registry, id(registry)
>     return func
> 
> if __name__ == '__main__':
>     import xlib
>     print registry, id(registry)
> 
> The library xlib just defines two dummy functions:
> 
> $ cat xlib.py
> from x import dec
> 
> @dec
> def f1():
>     pass
> 
> @dec
> def f2():
>     pass
> 
> Then I get the following output:
> 
> $ python x.py
> {'f1': <function f1 at 0x7f7bce0cd668>} 27920352
> {'f1': <function f1 at 0x7f7bce0cd668>, 'f2': <function f2 at
> {0x7f7bce0cd6e0>} 27920352 } 27395472
> 
> This is surprising since I would expect to have a single global
> dictionary, not two: how comes the registry inside the ``if __name__ ==
> '__main__'`` block is different from the one seen in the library?
> 
> This is python 2.7.3 on Ubuntu.

Welcome to python -- this is a trap every newbie falls into ;)

Seriously, you shouldn't use the main script as a library; it is put into 
the sys.modules cache under the "__main__" key. Subsequent imports under its 
real name will not find that name in the cache and import another instance 
of the module, with puzzling effects, like

$ cat x.py 
import x
class A: pass
a = A()
assert isinstance(a, x.A)

$ python x.py 
Traceback (most recent call last):
  File "x.py", line 4, in <module>
    assert isinstance(a, x.A)
AssertionError
$ 





More information about the Python-list mailing list