String representation of an identifier's name

Christopher A. Craig list-python at ccraig.org
Wed Jan 15 13:00:56 EST 2003


"Colin J. Williams" <cjw at sympatico.ca> writes:

> inspect is interesting, but it doesn't seem to give the name of an
> integer.

I can't tell if you're the original poster or not, but you're not
going to find anything all that interesting.

The id() function guarantees that it never has the same return for two
different objects in memory (in CPython it returns the memory
address), so we can use it to see if two names are the same object.

Python 2.2.1 (#1, Sep  7 2002, 14:34:30) 
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> global_var=t=t2=6
>>> id(global_var)
135274096
>>> id(t)
135274096
>>> id(t2) # all three globals are names for the same object
135274096
>>> t3=6
>>> id(t3)  # a name bound after the others still shares an object
135274096
>>> def eggs(a):
...   def spam(b):
...     from sys import getrefcount
...     print id(global_var)
...     print id(a)
...     print id(b)
...     print getrefcount()
...     # Point A
...   spam(a)
... 
>>> eggs(global_var) # all three names in three scopes are the same object
135274096
135274096
135274096
19

If you had some function fn(a) than given object "a" returned its
name, then at "Point A" above it would have 19 different names by
which the integer object '6' is currently called.  Getting those 19
names is very difficult because the namespace mappings are only
designed to go the other way, but even if you could get them it
doesn't seem to me to be all that useful.

-- 
Christopher A. Craig <list-python at ccraig.org>
I develop for Linux for a living, I used to develop for DOS.  Going from
DOS to Linux is like trading a glider for an F117. - Lawrence Foard





More information about the Python-list mailing list