A class question

Carl Banks pavlovevidence at gmail.com
Mon Oct 29 05:35:19 EDT 2007


On Oct 28, 6:01 am, Donn Ingle <donn.in... at gmail.com> wrote:
> Hello,
>
> Is there a way I can, for debugging, access the instance variable name from
> within a class?
> E.g:
> Class X:
>  def debug(self):
>   print "My instance var is %s" % (some magic Python stuff)
>
> So that:
>
> >>>x = X()
> >>>x.debug()
> >>>My Instance var is x
>
> ( Without passing the name in like: x=X(name="x") )


You could search the global and local namespaces of the caller for a
symbol that's bound to the same object as self.  For instance, to find
a such a symbol in the caller's global namespace, this might work:

def debug(self):
    for sym,value in sys._getframe(1).f_globals:
        if value is self:
            print "My instance var is %s" % sym

Improving the example left as an exercise.  There's probably quite a
few recipes to do stuff like this in the Python Cookbook (quod
googla).

Also, note that some objects are not bound to any symbols but instead
are referenced by lists or other containers.


Carl Banks




More information about the Python-list mailing list