[Tutor] What's in a name?

Walter Prins wprins at gmail.com
Sat Jan 4 00:56:12 CET 2014


Hi,

The code in my last post got line wrapped which will break if directly
tried out.  To avoid possible confusion I paste a version below with
shorter lines which should avoid the problem:


import gc, itertools

def names_of(obj):
    """Try to find the names associated to a given object."""
    #Find dict objects from the garbage collector:
    refs_dicts = (ref for ref in gc.get_referrers(obj)
                  if isinstance(ref, dict))
    #Get a single chained generator for all the iteritems() iterators
    #in all the dicts
    keyvalue_pairs = itertools.chain.from_iterable(
                        refd.iteritems() for refd in refs_dicts)
    #Return a list of keys (names) where the value (obj) is the one
    #we're looking for:
    return [k for k, v in keyvalue_pairs if v is obj]

x = []
y = x
z = [x]

print names_of(z[0])


More information about the Tutor mailing list