Skip to content

Instantly share code, notes, and snippets.

@ktosiek
Created December 6, 2020 14:11
Show Gist options
  • Save ktosiek/06bab25210a9b62996ae08d0eedab9ad to your computer and use it in GitHub Desktop.
Save ktosiek/06bab25210a9b62996ae08d0eedab9ad to your computer and use it in GitHub Desktop.
Find names of live instances of a Python class
import gc
from itertools import chain
from weakref import WeakKeyDictionary
from signals import Signal
import signals.other_file # noqa
def find_instance_names(cls: type):
results = WeakKeyDictionary()
__marker = object()
for instance in gc.get_referrers(cls):
if isinstance(instance, cls):
results[instance] = set(chain.from_iterable(
get_instance_names(r, instance) for r in gc.get_referrers(instance)
if isinstance(r, dict) and r.get('__marker') is not __marker))
return results
def get_instance_names(module_dict, instance):
base = module_dict.get('__name__') or '(unknown)'
for name in keys_by_value(module_dict, instance):
yield f"{base}.{name}"
def keys_by_value(d, needle):
for k, v in d.items():
if v is needle:
yield k
print(f"done: {dict(find_instance_names(Signal))}!")
# signals/__init__.py
class Signal:
def __init__(self):
pass
sig_a = Signal()
# signals/other_file.py
from signals import Signal
sig_b = Signal()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment