Classes & Instances

Alex Martelli aleax at aleax.it
Thu Jan 3 08:37:52 EST 2002


"Mark McEahern" <marklists at mceahern.com> wrote in message
news:mailman.1010000166.31356.python-list at python.org...
> original post essentially asked:
>
> how do I get an instance's name?
>
> pseudocode:
>
>   class A:
>     def instanceName(self):pass
>
>   f = a()
>
>   print f.instanceName # should print "f"
>
> a tangential suggestion might be to look into implementing one of the
> creational patterns from GoF in Python to control the creation of class
> instances, thereby allowing you to keep track of them.

You need no such complication to "keep track of" a class's instances --
it's easy and idiomatic to do it e.g. by appending a reference (I'd
suggest a weakref) to a per-class list in the instance's __init__, for
example.

This has nothing to do with *NAMES*, and the fact that the original
poster's request, properly translated into "how do I get the name
to which, in the future, the instance that is being created right
now will be bound" has no Python solution.  First of all, Guido would
have to insert in Python his beloved time machine, because, as the
instance is being created, no name yet is bound to it.  Even that
would not make things SIMPLE -- what "name" should be returned in
the case of
    somelistorother.append(a())
or
    x=y=z=t=a()
or
    f(a(),a(),a(),a())
or...?!

The only solution is apparently an exhaustive search, AFTER the
binding has taken place, into all possile "names" that MIGHT now
be bound to the generated instance (some careful definition will
be needed regarding attributes, since of course after
    x.y = a()
there's no guarantee whatsoever that x.y is bound to the same
object... maybe x.ZZZ might now be, or ...).

It's not worth it.  Maybe in some kind of debugging mode for a
development-environment, but I have my doubts even then.


Alex






More information about the Python-list mailing list