Getting the name of an assignment

Steven Bethard steven.bethard at gmail.com
Sat Dec 23 21:54:29 EST 2006


Adam Atlas wrote:
> Is it possible for an object, in its __init__ method, to find out if it
> is being assigned to a variable, and if so, what that variable's name
> is? I can think of some potentially ugly ways of finding out using
> sys._getframe, but if possible I'd prefer something less exotic.
> (Basically I have a class whose instances, upon being created, need a
> 'name' property, and if it's being assigned to a variable immediately,
> that variable's name would be the best value of 'name'; to make the
> code cleaner and less redundant, it would be best if it knew its own
> name upon creation, just like functions and classes do, without the
> code having to pass it its own name as a string.)

As others have mentioned, in general the answer is no.  However, class 
statements do have access to the name they're assigned, so you could 
abuse a class statement like this::

     >>> # your class whose instances need a name property
     >>> class C(object):
     ...     def __init__(self, name):
     ...         self.name = name
     ...     @classmethod
     ...     def from_class_block(cls, name, bases, blockdict):
     ...         return cls(name)
     ...
     >>> # instances of your class with the appropriate names
     >>> class instance:
     ...     __metaclass__ = C.from_class_block
     ...
     >>> instance.name
     'instance'

Though it doesn't rely on private functions like sys._getframe, it's 
still sure to confuse the hell out of your users. ;-)

STeVe



More information about the Python-list mailing list