Can I get a value's name

Scott David Daniels Scott.Daniels at Acm.Org
Mon May 11 13:18:18 EDT 2009


jalanb3 wrote:
> ... Given a variable name I can use locals() to get the value
>     Is there a way to do it the other way round
>         Given the value, can I get the variable name ?

(1) Yes you can in some cases.
(2) You should not, things do not inherently have a name.

With that prelude:
     def find_names(value, dictionary):
         for name, val in dictionary.items():
             if val is value: # note: "is", not "=="
                 yield name

     x = 123456
     y = 123456 * 3 // 3
     z = 123456.0
     q = y
     print list(find_names(y, locals()))

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list