Getting the name of an instance

Michael Hudson mwh at python.net
Thu Jan 17 05:17:18 EST 2002


"Tal Linzen" <pachy at 012.net.il> writes:

> Hi.
> 
> Suppose I have:
> p = MyClass()
> 
> I'm looking for a function that works like:
> func(p) = 'p'
> (meaning, retrieves the actual name of the variable).
> 
> The best I could come up with is:
> def func(p):
>     return globals().keys()[globals().values().index(p)]
> 
> Surely there's a simpler way, something like the __name__
> method in module objects.

>From http://www.amk.ca/quotations/python-quotes/page-8.html:

   The same way as you get the name of that cat you found on your
   porch: the cat (object) itself cannot tell you its name, and it
   doesn't really care -- so the only way to find out what it's called
   is to ask all your neighbours (namespaces) if it's their cat
   (object)...

   ....and don't be surprised if you'll find that it's known by many
   names, or no name at all!
                                          Fredrik Lundh, 3 Nov 2000

one of many quotes that should really be memorised by everyone
associated with Python....

Cheers,
M.


-- 
     ARTHUR:  Why are there three of you?
  LINTILLAS:  Why is there only one of you?
     ARTHUR:  Er... Could I have notice of that question?
                   -- The Hitch-Hikers Guide to the Galaxy, Episode 11



More information about the Python-list mailing list