Skip to content

Instantly share code, notes, and snippets.

@dichharai
Last active October 24, 2022 05:03
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 dichharai/0f3942afcdc404912903557200680611 to your computer and use it in GitHub Desktop.
Save dichharai/0f3942afcdc404912903557200680611 to your computer and use it in GitHub Desktop.
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