Last active
October 24, 2022 05:03
-
-
Save dichharai/0f3942afcdc404912903557200680611 to your computer and use it in GitHub Desktop.
This file contains 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 weakref | |
import gc | |
import ctypes | |
class PriceyObject: | |
def __init__(self, name): | |
self.name = name | |
def __repr__(self): | |
return f'PriceyObject({self.name})' | |
def __del__(self): | |
print(f'Deleting {self}') | |
def demo(cache_factory): | |
print(f'cache type: {cache_factory}') | |
strong_ref_obj_coll = [] | |
cache = cache_factory() | |
for gem in ['opal', 'ruby', 'fluorite']: | |
pobj = PriceyObject(gem) | |
print(f'reference count after initialization gem {gem}: {ctypes.c_long.from_address(id(pobj)).value}') | |
cache[gem] = pobj | |
print(f'reference count after caching gem {gem}: {ctypes.c_long.from_address(id(pobj)).value}') | |
strong_ref_obj_coll.append(pobj) | |
print(f'reference count after appending to list gem {gem}: {ctypes.c_long.from_address(id(pobj)).value}') | |
del pobj # decreasing reference count | |
print(f'List length: {len(strong_ref_obj_coll)}, contents: {strong_ref_obj_coll}') | |
print('cleaning list...') | |
del strong_ref_obj_coll | |
gc.collect() | |
print(f'After cleaning list, cache contains: {cache.keys()}') | |
for gem, gem_obj in cache.items(): | |
print(f'{gem}={gem_obj}') | |
print('demo returning') | |
return | |
demo(dict) | |
print('\n\n') | |
demo(weakref.WeakValueDictionary) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment