Skip to content

Instantly share code, notes, and snippets.

@BartMassey
Created May 17, 2018 19:27
Show Gist options
  • Save BartMassey/8eb2ad1faf83afd210f796f037773982 to your computer and use it in GitHub Desktop.
Save BartMassey/8eb2ad1faf83afd210f796f037773982 to your computer and use it in GitHub Desktop.
Demonstration of need for garbage collection in Python
# Copyright (c) 2018 Bart Massey
# GC demo.
# Create a circular structure. The reference
# count of x and y would be 2: one for the
# variable and 1 for the internal reference.
x = [1]
y = [2]
y[0] = x
x[0] = y
# Python has special-case code for printing this.
print(x)
# Drop a reference. The reference count
# of y would go from 2 to 1.
y = None
print(x)
# Drop the other reference. The reference count of
# x would go from 2 to 1. The structure is now
# unreachable, but nothing will be freed until
# the garbage collector runs.
x = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment