Holding reference to out of scope object's method
<pre><code>class Foo:
    def __init__(self, _label):
        self.label = _label
    def display(self):
        print(str(self.label))
    def get_display(self):
        return self.display

display_test = Foo(1).get_display()
display_test()
def inner_scope():
    global display_test
    display_test = Foo(2).get_display()
inner_scope()
display_test()
</code></pre>

<p>In Python 2.7, the above block prints 1 followed by 2, which isn't terribly surprising. What I'm curious about, though, is what happens to the objects generated by <code>Foo(1)</code> and <code>Foo(2)</code> -- it appears as though they have not been garbage collected as of the time <code>display_test</code> gets invoked, but does that mean <code>display_test</code> has a reference to <code>Foo(2)</code>, preventing it from being garbage collected at all? Am I just getting lucky that the objects aren't garbage collected before I invoke <code>display_test</code>? Does this differ in <code>3.x</code>?</p>

<p>Your question is a bit unclear.  This sentence: "it appears as though they have not been garbage collected as of the time display_test gets invoked" suggests some confusion.  In fact <code>display_test</code> gets invoked twice - one when it's bound to an instance method of Foo(1), and again when it's bound to instance method of Foo(2).  Until the call to <code>inner_scope</code>, display_test holds a reference to Foo(1) so it won't be GC'd.  After the call to <code>inner_scope</code> there is no longer any reference to Foo(1) so it is ready for GC.  But display_test now holds a reference to Foo(2) so <em>that</em> won't get GC'd.  So "they" - the objects Foo(1) and Foo(2) - don't get GC'd together but one at a time, each object's GC depending independently on whether there is any live reference to it.</p>

<p>Don't worry about the Python garbage collector.  It works beautifully.</p>

python python-2.7 python-3.x garbage-collection