How to obtain an instance's name at runtime?

Jim Meier fatjim at home.com
Wed Jun 23 13:02:24 EDT 1999


"Dinu C. Gherman" wrote:

> This is a nasty question, perhaps, so I appologize in
> advance if its stupidity level is far above the accepted
> average in this newsgroup...
>
> I would like to do the following:
>
> >>> class C:
> ...    pass
> ...
> >>>
> >>> c = C()
> >>> C.__class__.__name__ # ok
> 'C'
> >>> c.__name__           # not ok
> Traceback (innermost last):
>   File "<interactive input>", line 0, in ?
> AttributeError: __name__
> >>>
>
> Question: How to obtain an instance's name at runtime?
> That is I'd like to see this happen (one was or the other):
>
> >>> c.__name__
> 'c'
>
> I've checked the reference manual, but it's silent about
> this topic or I'm too blind...
>
> Fearing-there's-no-such-solution'ly,
>
> Dinu

Well, there sort of is a solution, but I don't think you're going to
like it. Incidentally, why are you trying to discover this? I'm not a
super-meister-coder, but I can't imagine a situation where knowing this
would be useful.

There are some problems in the way of what you want. First of all, there
is not actual name for the instance. The instance is a nameless object.
It only gets a 'name' by being referenced by a variable. And that name
can change. For example,

c=C()
d=c

At this point there are two references to the instance; which one is
it's 'name'? The same thing happens during function calls. For example,

def func(f):
    print 'this is my f:' + str(f)

c=C()
func(c)

The function gives it it's own new name. So you already have given the
instance a name!

But if you are just running in the interactive loop, and understand the
above problems, you could try this:

names=[]
for i in locals().items():
    if id(i[1]) == id(var):
        names.append(id[0])

Which should give you a list of the names of all the references to the
object IN THE CURRENT SCOPE.




-Jim





More information about the Python-list mailing list