Skip to content

Instantly share code, notes, and snippets.

@chobits
Created April 5, 2012 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chobits/2310716 to your computer and use it in GitHub Desktop.
Save chobits/2310716 to your computer and use it in GitHub Desktop.
Python: how to create finalizer garbage
import gc
class A():
# For Python, finalizers means instance objects with __del__ methods.
def __del__(self):
pass
print gc.garbage
# []
# create a finalizer garbage: a
a = A() # refcnt: 1
a.reference_cycle = a # refcnt: 2
del a # refcnt: 1 (become garbage)
# garbage collection doesnt work on `a` because of finalizer,
# so gc moves `a` to garbage list
gc.collect()
print gc.garbage
# [<__main__.A instance at 0xb780560c>]
# Python programmers should take care not to create such things.
# The programmer has to deal with this if they insist on creating
# this type of structure.
del gc.garbage[:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment