Skip to content

Instantly share code, notes, and snippets.

@prakashsellathurai
Last active April 12, 2026 18:29
Show Gist options
  • Select an option

  • Save prakashsellathurai/ea7ba0ec8a5cf049881464d34de31411 to your computer and use it in GitHub Desktop.

Select an option

Save prakashsellathurai/ea7ba0ec8a5cf049881464d34de31411 to your computer and use it in GitHub Desktop.
import gc
import sys
import weakref
class C:
def __add__(self, other):
return NotImplemented
def __pow__(self, other, mod=None):
return NotImplemented
def __eq__(self, other):
return NotImplemented
# dead proxy
obj = type("D", (), {})()
dead = weakref.proxy(obj)
del obj
gc.collect()
# live proxy
live_obj = C()
live = weakref.proxy(live_obj)
def run(label, func):
before = sys.gettotalrefcount()
for _ in range(10000):
try:
func()
except ReferenceError:
pass
after = sys.gettotalrefcount()
print(
f"{label}: leaked {after - before} refs (~{(after - before) // 10000}/call)"
)
# ---- tests ----
# binary
run("binary +", lambda: live + dead)
# ternary (pow with mod)
run("ternary pow", lambda: pow(live, dead, 3))
# comparisons
run("compare ==", lambda: live == dead)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment