Mailing List Archive

How to obtain an instance's name at runtime?
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

PS: Do not use my Deja email-address.


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
How to obtain an instance's name at runtime? [ In reply to ]
Dinu C. Gherman <gherman@my-deja.com> wrote:

>>>> 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 instance doesn't have a name. Take for example:

>>> a = b = c = C()

That creates one instance of C, with three references to it.
Now what is the `real' name of the instance?

Cheers, Frank

--
The suit into which the man's body had been stuffed looked as if it's only
purpose in life was to demonstrate how difficult it was to get this sort of
body into a suit.
-- Douglas Adams, 'The Restaurant at the End of the Universe'
How to obtain an instance's name at runtime? [ In reply to ]
> 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__
> >>>

Huh?

Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> class C:
... pass
...
>>> c = C()
>>> c.__class__.__name__
'C'
>>> C.__name__
'C'
>>> c.__name__
Traceback (innermost last):
File "<stdin>", line 1, in ?
AttributeError: __name__
>>> C.__name__
'C'
>>>
Use c.__class__.__name__!

Thomas Heller
ION-TOF GmbH
How to obtain an instance's name at runtime? [ In reply to ]
* Dinu C. Gherman
|
|
| 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'

How do you want this to behave if you go on from the situation you
have to type:

>>> d=c
>>> d.__name__
???
>>> c.__name__
???

--Lars M.
How to obtain an instance's name at runtime? [ In reply to ]
Dinu C. Gherman writes:

> >>> 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'
>
> Fearing-there's-no-such-solution'ly,

Do not fear! Simply write

>>> c.__class__.__name__
'C'
How to obtain an instance's name at runtime? [ In reply to ]
Please ignore my previous reply to this question, I replied *way* too
quickly without properly understanding what Dinu was looking for.

sometimes-I-wish-there-were-a-delay-on-outgoing-mail-ly y'rs,

-cgw
How to obtain an instance's name at runtime? [ In reply to ]
"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
How to obtain an instance's name at runtime? [ In reply to ]
Dinu C. Gherman <gherman@my-deja.com> 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

There is not reliable solution because instances are not named except as
part of a possible class behavior (__init__ setting self.__name__).
(It is the behavior of classes themselves to have names.)

But you can at least find some of the names bound to this object (within
the current scope, or beyond).

def whatname(obj):
import sys
try:
raise SystemError
except:
tb = sys.exc_info()[-1]
f = tb.tb_next.tb_frame
locals = f.f_locals
globals = f.f_globals
del tb, f
for key, item in locals.items() + globals.items():
if item is obj:
break
else:
raise NameError, 'object not found' # kind of a reverse namelookup ;)
return key

This is inaccurate because the object could be passed down from another
module, thru numerous function calls. And the same could be done for
classes:
>>> class C:
... pass
>>> A = C
>>> c = A()
>>> c.__class__.__name__
'C'
>>>

To make the behavior, then set the "__name__" attribute in the
constructor.
class C:
def __init__(self, name='c'):
self.__name__ = name
b = C('b')

It may not be what you want, but then Python doesn't quite work like
you might suspect. :)

-Arcege
How to obtain an instance's name at runtime? [ In reply to ]
In article <7kqrc5$9fs@cs.vu.nl>,
Frank Niessink <frankn=news@cs.vu.nl> wrote:
> Dinu C. Gherman <gherman@my-deja.com> wrote:
>
> > Question: How to obtain an instance's name at runtime?
>
> That instance doesn't have a name. Take for example:
>
> >>> a = b = c = C()
>
> That creates one instance of C, with three references to it.
> Now what is the `real' name of the instance?

Very true, very true - I new there was something good about
Python, here: object references, making something else rather
impossible! Still, I wish it was possible to access the "name
administrator" somewhere deep inside the Python interpreter to
have that. I'll give more reasons for that only in a couple
of days, I hope... Sorry for not being more precize, now!

Dinu



Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
How to obtain an instance's name at runtime? [ In reply to ]
Maybe I'm missing the point here.
I use this approach which shows the class name and an address for the
instance. That's about as good a name as I can imagine possible for that
instance. Unless you start adding name attributes.

>>> class A:
... pass
...
>>> a=A()
>>> str(a)
'<__main__.A instance at 7f6350>'

If you want to keep track of the name of the variable that your instance is
contained within. Then I don't think this is possible because it would
require that each instance keep a list of the variables that it was stored
in. Even then you would be faced with a list instead of a single name.
>>> str(b)
'<__main__.A instance at 7f6350>'
--
--Darrell
How to obtain an instance's name at runtime? [ In reply to ]
"Dinu C. Gherman" wrote:
> Question: How to obtain an instance's name at runtime?

An *instance's* name? Instances have names?

> >>> c.__name__
> 'c'

Are you actually looking to have the instance tell you what the variable is?
Wouldn't that be both [0]pointless and [1]meaningless, because [1]you already
know what the variable is, otherwise you can't use it, and [2]the variable-name
isn't necessarily the least bit unique, with regard to the variable to which it
referrs?
Classes have names, and I don't beleive that instances do, because, well...,
the name of the class tells what the class is (as far as `what kind of object
it is'--I don't really know how to expand on that, except with an analogy like
`what species an animal is'), and it usually goes without saying that `what
kind of object it is', with regard to C(), is C().__class__ (or
C().__class__.__name__, if you want a label rather than an object).


-Rozzin.
How to obtain an instance's name at runtime? [ In reply to ]
In article <37718424.C70BB9DE@geekspace.com>, says...
>
>"Dinu C. Gherman" wrote:
>> Question: How to obtain an instance's name at runtime?

rozzin@geekspace.com responded:
> An *instance's* name? Instances have names?

and others similarly.

As near as I can remember, only three types of objects have definition
names (in readonly? __name__ attributes): modules, functions, and
classes. All others are anonymous, though they may or may not have one
or more namespace references.

While named objects usually get a namespace (reference) name equal to
the definition name, there is no necessary connection. Consider:

def f(): pass
g=f
del f

Now the function which internally thinks of itself as 'f' is referred to
externally as 'g' and only as 'g'.

Terry J. Reedy
How to obtain an instance's name at runtime? [ In reply to ]
Terry Reedy wrote:
> As near as I can remember, only three types of objects have definition
> names (in readonly? __name__ attributes): modules, functions, and
> classes. All others are anonymous, though they may or may not have one
> or more namespace references.
>
> While named objects usually get a namespace (reference) name equal to
> the definition name, there is no necessary connection. Consider:
>
> def f(): pass
> g=f
> del f
>
> Now the function which internally thinks of itself as 'f' is referred to
> externally as 'g' and only as 'g'.

Yes, it makes sense for functions, classes, and modules to all have names,
because they are all -definers-, which is what I think I was trying to say.
Instances aren't `definers'--they don't act as the root of the definition for
`what something is'.

-Rozzin.
How to obtain an instance's name at runtime? [ In reply to ]
Joshua Rosen wrote:
>
> Instances aren't `definers'--they don't act as the root of the definition for
> `what something is'.

I think it's more a matter of the fact that the syntaxes for
creating classes and functions happen to incorporate a name,
which Python squirrels away just in case someone is interested
later (which they often are).

When an instance is created, on the other hand, there is
no obvious name available. So, if you want one, you have to
arrange for it yourself.

Greg
How to obtain an instance's name at runtime? [ In reply to ]
In article <3771127C.E40F9BF3@home.com>,
Jim Meier <fatjim@home.com> wrote:
>
> 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.

Ok, I knew I was going to look like a dumb camel right after
posting my question... Nevertheless there is a useful case of
knowing such an instance's name, at least I believe I found
one. Have a look at the following page, spot the question mark
and you'll know what I mean:

http://starship.python.net/crew/gherman/UMLgenTest.pdf

But, PLEASE, don't start to ask me anything about the project
itself!! It's all in a very pre-pre-pre-alpha phase...

There might be some workaround solution in oder to get that
name I want, as in some of the replied in this thread, but
I'll evaluate that later...

Regards,

Dinu



Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
How to obtain an instance's name at runtime? [ In reply to ]
I'm new at this, but it seems I've read that the tracestack is
available. Might it be possible to read in the calling line number,
then parse the source code for your 'name'?

--

Emile van Sebille
emile@fenx.com
-------------------
How to obtain an instance's name at runtime? [ In reply to ]
On Fri, 25 Jun 1999, Dinu C. Gherman wrote:

> In article <3771127C.E40F9BF3@home.com>,
> Jim Meier <fatjim@home.com> wrote:
> >
> > 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.
>
> Ok, I knew I was going to look like a dumb camel right after
> posting my question... Nevertheless there is a useful case of
> knowing such an instance's name, at least I believe I found
> one. Have a look at the following page, spot the question mark
> and you'll know what I mean:
>
> http://starship.python.net/crew/gherman/UMLgenTest.pdf
>
> But, PLEASE, don't start to ask me anything about the project
> itself!! It's all in a very pre-pre-pre-alpha phase...
>
> There might be some workaround solution in oder to get that
> name I want, as in some of the replied in this thread, but
> I'll evaluate that later...


It's easy to get *A* name --

Classes and functions have cannonical names in Python because Python
distinguishes between definition and assignment for classes and
functions. They also have a cannonical namespace -- for classes,
their __module__ attribute, for Python functions, their func_globals
attribute (which is the __dict__ of the __module__ they were defined
in.) That's why their names are "sticky" .

Classes and functions can be aliased and assigned to other names,
but for debugging, tracebacks and printing, you want that cannonical
defining name.

There are other types of objects that could benefit from "sticky"
names: constants and enumns for example. But Python doesn't
have a different syntax to indicate a definition separate from
any other assignment.


You can get a name by searching for the thing in all of the namespaces:

>>> def findname(thing):
... for mod in sys.modules.values():
... for name,val in mod.__dict__.items():
... if val is thing : return name

>>> findname( sys.stdin )
'stdin'
>>> findname( findname )
'findname'

>>> findname( lambda x: x+1 ) # anonymous function doesn't have a name
# returns None

>>> xxx = sys.stdin # alias sys.stdin to another name
>>> findname( sys.stdin ) # finds *a* name (whichever is first)
'xxx'


# Try the __name__ attribute first before searching...

>>> def nameof( THING ):
... return getattr( THING, '__name__', None ) or findname( THING )
...


>>> nameof( lambda x: x+1 )
'<lambda>'
>>> mod = sys
>>> nameof( mod )
'sys'


[1] You could do a smarter seach of the name space, but I'm not sure
if that would be any better for your application.

[2] You could also append the module name to the name and return
"sys.stdin" rather than "stdin" above.

[3] Might there be cases where you want the '__repr__' rather than
the name ? i.e. "<open file '<stdin>', mode 'r' at 5a28500>" rather
than "stdin"



---| Steven D. Majewski (804-982-0831) <sdm7g@Virginia.EDU> |---
---| Department of Molecular Physiology and Biological Physics |---
---| University of Virginia Health Sciences Center |---
---| P.O. Box 10011 Charlottesville, VA 22906-0011 |---

"IA-64 looks just about like what you would expect from a PA-RISC
and IA-32 train wreck with a little VLIW thrown in for spice."
* Thomas J. Merritt <tjm@spam.codegen.com> in <news:comp.arch> *
How to obtain an instance's name at runtime? [ In reply to ]
"Dinu C. Gherman" wrote:
>
> Have a look at the following page, spot the question mark
> and you'll know what I mean:

I've looked at the page, and it helps, but still
doesn't provide enough information to tell exactly
what you want the "name" of the object to be.

The best solution by far would be to give the
object a name explicitly when you create it.
Is this possible, or do you want to retrofit
it onto existing code?

It looks like you want it to be something like
"the name of the first variable to be assigned
a reference to the object". Does this apply to
local variables as well as globals? Instance
variables of another object? What if the object
is never assigned to a variable? What if it
is, but somewhere far removed from where it
is created?

Greg
How to obtain an instance's name at runtime? [ In reply to ]
From: "Tim Peters" <tim_one@email.msn.com>

[Dinu C. Gherman]
> ...
> Just that much: an object, that has not been assigned
> a name to, cannot exist (having a reference count of
> zero), can it (at least for user-defined objects)?

There must be a way to "get to" it, but access paths needn't be names; e.g.,

week = [Day("Sunday"), Day("Monday"), ...]

The object constructed by Day("Monday") was never given a name, and is
accessible only via the access path week[1] (or equivalent from the end of
the list).

anonymously y'rs - tim
How to obtain an instance's name at runtime? [ In reply to ]
In article <37769B92.47EBE99C@compaq.com>,
Greg Ewing <greg.ewing@compaq.com> wrote:
>
> The best solution by far would be to give the
> object a name explicitly when you create it.
> Is this possible, or do you want to retrofit
> it onto existing code?

The latter is what I'm planning to do.

> It looks like you want it to be something like
> "the name of the first variable to be assigned
> a reference to the object". Does this apply to
> local variables as well as globals? Instance
> variables of another object? What if the object
> is never assigned to a variable? What if it
> is, but somewhere far removed from where it
> is created?

You're guessing very well... ;-) Actually, I will
postpone some issues until some advance is made at
other places of the code.

Just that much: an object, that has not been assigned
a name to, cannot exist (having a reference count of
zero), can it (at least for user-defined objects)?

In any case thanks so far! I think the problem is not
a really fundamental one for the type of application
I'm having in mind, after all.

Bye,

Dinu





Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
How to obtain an instance's name at runtime? [ In reply to ]
From: Dinu C. Gherman <gherman@my-deja.com>

In article <37769B92.47EBE99C@compaq.com>,
Greg Ewing <greg.ewing@compaq.com> wrote:
>
> The best solution by far would be to give the
> object a name explicitly when you create it.
> Is this possible, or do you want to retrofit
> it onto existing code?

The latter is what I'm planning to do.

> It looks like you want it to be something like
> "the name of the first variable to be assigned
> a reference to the object". Does this apply to
> local variables as well as globals? Instance
> variables of another object? What if the object
> is never assigned to a variable? What if it
> is, but somewhere far removed from where it
> is created?

You're guessing very well... ;-) Actually, I will
postpone some issues until some advance is made at
other places of the code.

Just that much: an object, that has not been assigned
a name to, cannot exist (having a reference count of
zero), can it (at least for user-defined objects)?

In any case thanks so far! I think the problem is not
a really fundamental one for the type of application
I'm having in mind, after all.

Bye,

Dinu





Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
How to obtain an instance's name at runtime? [ In reply to ]
[Dinu C. Gherman]
> ...
> Just that much: an object, that has not been assigned
> a name to, cannot exist (having a reference count of
> zero), can it (at least for user-defined objects)?

There must be a way to "get to" it, but access paths needn't be names; e.g.,

week = [Day("Sunday"), Day("Monday"), ...]

The object constructed by Day("Monday") was never given a name, and is
accessible only via the access path week[1] (or equivalent from the end of
the list).

anonymously y'rs - tim