Python: how to “kill” a class instance/object?

In general:

  • Each binding variable -> object increases internal object’s reference counter
  • there are several usual ways to decrease reference (dereference object -> variable binding):

    1. exiting block of code where variable was declared (used for the first time)
    2. destructing object will release references of all attributes/method variable -> object references
    3. calling del variable will also delete reference in the current context
  • after all references to one object are removed (counter==0) it becomes good candidate for garbage collection, but it is not guaranteed that it will be processed (reference here):

CPython currently uses a reference-counting scheme with (optional)
delayed detection of cyclically linked garbage, which collects most
objects as soon as they become unreachable, but is not guaranteed to
collect garbage containing circular references. See the documentation
of the gc module for information on controlling the collection of
cyclic garbage. Other implementations act differently and CPython may
change. Do not depend on immediate finalization of objects when they
become unreachable (ex: always close files).

  • how many references on the object exists, use sys.getrefcount

  • module for configure/check garbage collection is gc

  • GC will call object.__ del__ method when destroying object (additional reference here)

  • some immutable objects like strings are handled in a special way – e.g. if two vars contain same string, it is possible that they reference the same object, but some not – check identifying objects, why does the returned value from id(…) change?

  • id of object can be found out with builtin function id

  • module memory_profiler looks interesting – A module for monitoring memory usage of a python program

  • there is lot of useful resources for the topic, one example: Find all references to an object in python

Leave a Comment