Last active
April 12, 2026 18:29
-
-
Save prakashsellathurai/ea7ba0ec8a5cf049881464d34de31411 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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