How to get an object's name as a string?

Duncan Booth duncan.booth at invalid.invalid
Wed Oct 29 14:49:00 EDT 2008


Steve Holden <steve at holdenweb.com> wrote:

>> That explanation makes no sense. Given the assignment:
>> 
>> x = 57
>> 
>> if the name of x isn't 'x', then what on earth can it possibly mean to 
>> ask for the name of a variable?
>> 
> He didn't ask for the name of a variable, he asked for the name of an
> object. You may choose to equate them, but they aren't the same thing.

When I do that assignment there seem to be 5 references to that object, two 
of them are dictionary keys (what's the name of a dictionary key?), and two
are dictionary values. the last one is of course x. Any of these seem a 
reasonable answer to the question, but how the code is supposed to tell
which name is the one the user wanted is another matter.

>>> import varname
>>> x = 57
>>> for s in varname.object_info(x):
...     print s
...
opcode.opmap['INPLACE_MULTIPLY']
encodings.cp850.encoding_map[57]
encodings.cp850.decoding_map[57]
dis.opmap['INPLACE_MULTIPLY']
__main__.x
>>>

When I repeat the experiment in Idle the cp850 encoding entries disappear so 
I only get a choice of 3 'names'.

> l = []
> l.append(l)
> del l
> 
> What's the name of the list formerly known as "l"?

My code thinks its name is <...>, but then that's just my code:

>>> l = []
>>> l.append(l)
>>> for s in varname.object_info(l):
	print s

	
__main__.l
<...>
>>> 




More information about the Python-list mailing list