How can I get the name of an object???
Mark Jackson
mjackson at wc.eso.mc.xerox.com
Wed Apr 26 14:39:34 EDT 2000
Sean Blakey <sblakey at freei.com> writes:
> 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.
Right. Consider also the following:
>>> a=999
>>> b=999
>>> c=b
>>> a is b
0
>>> b is c
1
All fine; c and b are the same, a just "happens" to be equal. But
>>> c=1
>>> d=1
>>> c is d
1
Because of implementation details (driven by considerations of
efficiency), there will be instances of "accidental" identity. Unless
the objective is tolerant of this, any scheme to find *the* name of an
object would seem to be doomed.
--
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
An advertiser will happily make you feel bad about
yourself if that will make you buy, say, a Bic pen.
- George Meyer
More information about the Python-list
mailing list