[Python-Dev] Unexpected increase of globals() refcount

Benjamin Peterson benjamin at python.org
Fri May 23 18:03:03 CEST 2014


On Fri, May 23, 2014, at 8:49, Chandra Srinivasan wrote:
> Hi,
> I ran the following code in the Python interpreter and am trying to
> determine if the behavior I see is expected:
> 
> import sys
> print sys.getrefcount(globals())
> class Foo(object):
>    def __init__(self):
>       pass
> print sys.getrefcount(globals())
> 
> The first print statement above prints '4' and the second one prints '5'.
> However, if I remove the __init__ method from the class, the refcount
> stays the same.
> 
> If I change the above code like this, the ref count stays the same:
> 
> import gc
> import sys
> print sys.getrefcount(globals())
> class Foo(object):
>    def __init__(self):
>       pass
> del Foo
> while gc.collect():
>   pass
> print sys.getrefcount(globals())
> 
> Can you let me know if this is a bug in the Python interpreter?

No, functions hold a reference to the globals of the module they are
defined in.


More information about the Python-Dev mailing list