Created
December 6, 2020 14:11
-
-
Save ktosiek/06bab25210a9b62996ae08d0eedab9ad to your computer and use it in GitHub Desktop.
Find names of live instances of a Python class
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 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))}!") |
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
# signals/__init__.py | |
class Signal: | |
def __init__(self): | |
pass | |
sig_a = Signal() |
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
# 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