object query assigned variable name?

Nick Craig-Wood nick at craig-wood.com
Fri May 1 14:30:05 EDT 2009


warpcat <warpcat at sbcglobal.net> wrote:
>  I've passed this around some other groups, and I'm being told
>  "probably not possible".  But I thought I'd try here as well :)   I
>  *did* search first, and found several similar threads, but they
>  quickly tangented into other specifics of the language that were a bit
>  over my head :)  At any rate, here's a simple example, I'd love to
>  know if as shown, is somehow possible:
> 
>  Given an object:
> 
>  class Spam(object):
>      def __init__(self):
>          # stuff....
> 
>  I'd like it to print, when instanced, something like this:
> 
> >>> s = Spam()
>  I’m assigned to s!
> 
>  But it seems prohibitively hard (based on my web and forum searches)
>  for an object to know what variable name is has been assigned to when
>  created.  Querying 'self' in __init__ returns a memory location, not
>  the variable name passed in.
> 
>  If you're wondering why I'm trying to figure this out, this is just
>  part of my continued learning of the language and pushing the bounds,
>  to see what is possible ;)
> 
>  Any thoughts?

Read up on introspection and learn how to look up through the stack
frames.

When you've mastered that look for an object matching self in all the
locals in those stack frames.

That will give some kind of answer.

I have no idea whether this will work - the keyboard of my phone is
too small to produce a proof ;-)

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list