grześ
grześ

Reputation: 497

Garbage collection and references to object's attributes

When there are no more references to an object, GC is supposed to get rid of it pernamently. But what happens when we still have references to object's attributes or methods?

For example, in the code below I still try to use a.x even though a was deleted. Is this a valid piece of code?

import gc

class A:
    def __init__(self, x):
        self.x = x

a = A(7)
x = a.x
del a
gc.collect()

print(x)  # is it going to work?

Does the answer change if I use a method instead of an attribute? For example:

import gc

class A:
    def __init__(self, x):
        self.x = x

    def method(self):
        print("A.method", self.x)

a = A(7)
f = a.method
del a
gc.collect()

f()  # is it going to work?

Upvotes: 0

Views: 101

Answers (1)

Slam
Slam

Reputation: 8572

Both pieces of code works.

Having referenced by anything will protect objects from being collected. In most cases parent objects/classes/closures included, because bounding actually does handle referencing chain "automatically"

Upvotes: 1

Related Questions