Determining names of instances

Penfold spam at spam.com
Mon Jan 15 18:45:51 EST 2001


"Daniel Klein" <DanielK at jBASE.com> wrote in message
news:e7L86.554$KD3.238565 at typhoon.aracnet.com...
> A question I hope has a simple answer. Take the following simple class and
> instance
>
>     class foobar:
>         pass
>
>     foo = foobar()
>
> The question is, is there a way for the object 'foo' to know that its name
> is 'foo'?

In short, no.  A longer answer is to say that it doesn't particularly make
sense to ask an object for its name.
Why?  Because in python objects exist and are referenced through "bindings".
Thus, 'foo' is not a name for the instance created by foobar(), it is simply
*one* particular binding for that object.  One of, in general, many.  The
statement foo = foobar() does not define a name for the object, it only
defines a binding in the current namespace.

Any particular object, may have many bindings in different namespaces and in
the same namespace.  For instance

    foo = foobar()
    flubber = foo
    print id(foo), id(flubber)

You'll see that both foo and flubber are the same object, same as in the
*exact same instance*.  So what is the name of the object ?  Both foo and
flubber are merely bindings, ways of getting at the object.  They are in no
way tied up with the object itself and thus *neither* can be names.

This of course is the simplest example. But what about other common ones.
eg
    L = [];L.append(foobar())

then L[0] obviously exists, but how exactly would you define a name for it ?
What about
    class X: pass
    x = X(); x.wibble = foobar()

Again, what is the "name" of the object, is it "x.wibble"?  No, the whole
question isnt particularly well defined.

However, if you are desperate to find the name of a *binding* for an object
you can do that simply by inspecting the globals()/locals()/whatever
namespace you're interested in.

Des.
>
> Daniel Klein
>
>





More information about the Python-list mailing list