Little Q: how to print a variable's name, not its value?

Duncan Booth duncan.booth at invalid.invalid
Thu Mar 31 03:13:30 EST 2005


stewart.midwinter at gmail.com wrote:

> But surely if you create an integer object and assign it a value, e.g.
> a = 3,
> why shouldn't Python be able to tell you something like the following:
> name(a)  >>> 'a'
> ?

But why should it return 'a' and not one of these?

tokenize.tok_name[3]
token.tok_name[3]
sre_parse.OPCODES['any_all']
sre_parse.CHCODES['category_not_space']
sre_parse.ATCODES['at_boundary']
sre_constants.OPCODES['any_all']
sre_constants.CHCODES['category_not_space']
sre_constants.ATCODES['at_boundary']
sre_compile.OPCODES['any_all']
sre_compile.CHCODES['category_not_space']
sre_compile.ATCODES['at_boundary']
opcode.opmap['ROT_THREE']
encodings.cp437.encoding_map[3]
encodings.cp437.decoding_map[3]
encodings.cp1252.encoding_map[3]
encodings.cp1252.decoding_map[3]
dis.opmap['ROT_THREE']
tokenize.STRING
token.STRING
stat.ST_NLINK
os.P_NOWAITO
nt.P_NOWAITO
locale.LC_MONETARY
imp.C_EXTENSION
_locale.LC_MONETARY

The important thing is that not only do these variables all have the value 
3, they all have the *same* value 3. That monstrous code I posted behaves a 
little differently if you give it a number such as 101:

>>> x = 101
>>> for s in varname.object_info(101):
...   print s
...
<anonymous tuple at 10292480>[0]

The variable 'x' is ignored because it contains a different 101, the only 
thing in the system using the specific 101 that was passed to object_info 
is the tuple used to contain the constants for the executing code. Asking 
for object_info(x) will indeed return only one string '__main__.x'.

The key here is to understand the difference between languages like C where 
a variable is a container used to store a value and Python where variables 
are simply the binding of names to objects.



More information about the Python-list mailing list