How to know whether the un-assigned object is released or not?

Hi,

for the following piece of code, after a = classB(), how to tell whether classA() object in line a = classA() is still in memory or not?

a = classA()
# do somethign else
a = classB()

After the name a is re-assigned to a different object, the first
object will be automatically deleted by the garbage collector if no
other references to the original object exist.

Normally you should just trust the interpreter to do its job of
collecting unused objects. It just works and you almost never need to
worry about it.

When and how that happens is not under your control, it depends on the
interpreter. Different interpreters (e.g. PyPy, Jython, IronPython,
CPython, etc) have different garbage collectors with different
characteristics.

Technically the garbage collector can also remove objects which take
part in an unreachable cycle, e.g. object A refers to B which refers to
C which refers back to A, but the cycle-breaker doesn’t run instantly.
That may take a few seconds or so.

But the reference count garbage collector runs instantly: as soon as the
number of references to an object hits zero, it is deleted.

In CPython, you can use the gc module to investigate objects being
tracked by the cycle-breaker garbage collector.

https://docs.python.org/3/library/gc.html

You can check the reference count of an object with
sys.getrefcount:

class A:
    pass

a = A()
count = sys.getrefcount(a)

The count returned is always 1 more than you expect (due to the
reference passed to the sys.getrefcount function itself), so if the
count is 2, then reassigning a will instantly delete the object,
unless it has a __del__ method, in which case it could be delayed
while the method runs.

Using __del__ is not recommended.

You can read more about Python’s garbage collectors here:

https://devguide.python.org/garbage_collector/

but honestly except for advanced use, you don’t need to care about it.
It just does its job.

1 Like

@steven.daprano
Many thanks for your professional answer!