Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #31038

Re: surprising behaviour of global dictionaries

From Peter Otten <__peter__@web.de>
Subject Re: surprising behaviour of global dictionaries
Date 2012-10-09 17:24 +0200
Organization None
References <40ac555b-71c2-445e-814b-6bd1d037dbee@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.2006.1349796256.27098.python-list@python.org> (permalink)

Show all headers | View raw


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
$ 

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

surprising behaviour of global dictionaries Michele Simionato <michele.simionato@gmail.com> - 2012-10-09 08:08 -0700
  Re: surprising behaviour of global dictionaries Peter Otten <__peter__@web.de> - 2012-10-09 17:24 +0200
    Re: surprising behaviour of global dictionaries Michele Simionato <michele.simionato@gmail.com> - 2012-10-09 08:36 -0700
      Re: surprising behaviour of global dictionaries Dave Angel <d@davea.name> - 2012-10-09 12:10 -0400
    Re: surprising behaviour of global dictionaries Michele Simionato <michele.simionato@gmail.com> - 2012-10-09 08:36 -0700
    Re: surprising behaviour of global dictionaries Grant Edwards <invalid@invalid.invalid> - 2012-10-09 15:53 +0000
      Re: surprising behaviour of global dictionaries Peter Otten <__peter__@web.de> - 2012-10-09 19:45 +0200

csiph-web