Search code examples
python-3.xclass-attributes

Why there are three references to the class attribute?


Let consider this code:

import sys
import gc

class A:
    a = "something here to print"
    def __init__(self):
        pass

a = A()
print(sys.getrefcount(A.a))  # prints 3


refs = gc.get_referents(A.a)
print(len(refs))             # prints 0

I don't understand why it prints 3. Where is the third reference?

And why gc.get_referents returns an empty list?


Solution

  • The documentation of sys answers the first part of your question:

    sys.getrefcount(object): Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

    Consider this for the second part of your question:

    import sys
    import gc
    
    
    class A:
        a = "something here to print"
        def __init__(self):
            pass
    
    a = A()
    print(sys.getrefcount(A.a))     # prints 3
    
    refs = gc.get_referents(A.a)
    print(len(refs))                # prints 0
    
    refs2 = gc.get_referrers(A.a)   # prints 2 (what you expected)
    print(len(refs2))
    

    See the documentation of both gc methods:

    gc.get_referents(*objs): Return a list of objects directly referred to by any of the arguments.[...]

    gc.get_referrers(*objs): Return the list of objects that directly refer to any of objs. [...]