python - Finding qualified names that reference a given object -
for debugging purposes, want obtain names under given object known; want qualified names (i.e., a.x
rather x
). here's our first attempt:
import gc, sys def find_names(obj): result = [] referrer in gc.get_referrers(obj): if isinstance(referrer, dict): k in referrer: if referrer[k] obj: n = '???' f in ('__qualname__', '__name__'): if f in referrer: n = referrer[f] result.append('{}.{}'.format(n, k)) return ','.join(result)
the problem cannot find "name" of container container unless container __dict__
of class or module (then __qualname__
or __name__
work). don't know why __class__
not part of instance's __dict__
(is stored in slots?), reason doesn't matter - matters can't it.
is there can work follows:
class a: pass = a() a.x = object() find_names(a.x) # want return `a.x` rather `???.x`
i think can checking referrers of referrer corresponds instance, , looking 1 __dict__
identical original referrer:
def find_names(obj): result = [] referrer in gc.get_referrers(obj): if isinstance(referrer, dict): k in referrer: if referrer[k] obj: n = '???' f in ('__qualname__', '__name__'): if f in referrer: n = referrer[f] break if n == '???': parents = gc.get_referrers(referrer) p in parents: if getattr(p, '__dict__', none) referrer: n = '<instance of class ' + p.__class__.__name__ + '>' result.append(str(n) + '.' + str(k)) return '\n'.join(sorted(result))
Comments
Post a Comment