Inverse of id()?

Paul McGuire ptmcg at austin.rr.com
Sat May 19 19:42:53 EDT 2007


Is there an inverse function to the builtin 'id'?  The poster who
asked about 1-to-1, 1-to-n, etc. relationships (presumably in CS terms
- I hope I didn't misread some porn spam by mistake), got me thinking
about containers and ids, and what kind of a container would implement
a many-to-many.

I happened to still have my Python interpreter open from noodling
about another poster's question, using named arguments and parse-time
functions in a regex, so I looked at the 'results' variable that
experiment generated (this was a quick way to work with a non-trivial
object, so if I reconstructed it from an id, I could test whether I
really got back the object):
>>> re = Regex("(\d*)").setResultsName("x").setParseAction(lambda t:int(t[0]))
>>> results = re.parseString("123")

pyparsing results have some special lookup behavior, that if the
results name is a Python-friendly identifier, can use the name as if
it were an object attribute:
>>> results.x
123

So I extracted the id of results, and then started looking for the
function that does the inverse of id.  Unfortunately, skimming through
the docs, I didn't find it, so I brute-force searched the globals()
dict:
>>> z = id(results)
>>> for x in globals().values():
...   if id(x)==z: break
...

This gives me a variable x that is indeed another ref to the results
variable:
>>> x is results
True
>>> x.x
123

Now is there anything better than this search technique to get back a
variable, given its id?

-- Paul




More information about the Python-list mailing list