How can I get the name of an object???

Sean Blakey sblakey at freei.com
Wed Apr 26 20:12:50 CEST 2000


Peter,
Python objects do not have any way of finding out what name they are
referenced by.  Names refer to objects, but objects do not have name.

This is reasonable, since it is simple for an object to have 0, 1, or
more names.  Imagine what an imaginary __name__ attribute would be in
the following cases:
>>>class A:
...  pass
...
>>>A().__name__		# What should this be? ''?
>>>a = A()
>>>b = a		# b and a are now two names for the same object
>>>b.__name__		# Should this be 'a', 'b', or ['a', 'b']?

There are some clever hacks to attempt this (like iterating through all
the names in globals() looking for a match with the object), but I have
not seen any that are completely effective.
def lookupName(object):
	'''
	Tries to find an object in the global dictionary.
	If the object is found, the name of that object is returned.
	Otherwise, the empty string is returned.
	'''
	for name, value in globals.items():
		if object is value:	# pointer comparison
			return name
	else:			# I know this "else" is unneeded, 
		return ''	#but it is what I mean

spex66 at my-deja.com wrote:
> 
> Hi again,
> 
> other trivial (looking) question:
> 
> >>> class zz: pass
> >>> dd = zz()
> 
> I cannot find the hook to get back the name of 'dd' as a string.
> Why? Cause I need the names for code generation :-)
> 
> like estimated
> >>> dd.__name__
> >>> 'dd' #DON'T WORK
> 
> any hacks available?
> 
> Peter
> (=PA=)
> 
> Sent via Deja.com http://www.deja.com/
> Before you buy.
> --
> http://www.python.org/mailman/listinfo/python-list

-- 
Sean Blakey
FreeInternet.com
sblakey at freei.com
(253)796-6500x1025




More information about the Python-list mailing list