name of an instance

Peter Otten __peter__ at web.de
Mon Nov 1 07:32:19 EST 2004


andrea valle wrote:

> Hi to all,
> another basic question, but...
> How do I access the name of an instance?
> 
> I.e., if I have:
> 
> class MyClass:
> def __init__(self):
> print "here we are, kids!"
> 
> and:
>  >>> a = MyClass()
> 
> I'd like to have:
> 
>  >>> 'a'

There is no such thing as a name for an object, as many names in many scopes
may refer to the same object. The object has no way of knowing which names
refer to it.
However, you can take the brute force approach and just scan the scope you
are interested in, which may or may not be useful for debugging purposes.

>>> class T: pass
...
>>> a = b = T()
>>> c = T()
>>> def namesFor(obj, scope):
...     return [n for (n, v) in scope.iteritems() if v is obj]
...
>>> namesFor(a, globals())
['a', 'b']
>>> namesFor(c, globals())
['c']

And now with different scopes:

>>> import sys
>>> from sys import path as sys_path
>>> namesFor(sys_path, globals())
['sys_path']
>>> namesFor(sys_path, vars(sys))
['path']

Peter




More information about the Python-list mailing list