pythonrefcounting

Python reference count


In the following Python code:

class Foo:
    def bar(self):
        return 1

def baz():
    return Foo()

print baz().bar()

Question 0:

When bar() is evaluated in print baz().bar(), what make the Foo instance returned by baz() to have not yet been garbage collected, since it seems there is no reference to it, like there would be in:

foo = baz()
print foo.bar()

where foo store a reference of the Foo instance.

Question 1:

If Foo and baz were implemented in C in a Python extension module, should baz increment the reference count of the returned object foo to set it to 1?


Solution

  • Answer 0: when bar() is called, bar is a bound method (bound to the Foo instance), which keeps a reference to its self argument, which is the Foo instance.