Getting the name of a variable which was used as a function parameter.

Ravi Kotecha kotecha.ravi at googlemail.com
Mon Jul 21 18:01:10 CEST 2008


Hi guys,

I thought this was pretty cool and since I spent 30 mins or so
goggling before giving up and figuring out myself I thought I'd share
it with you.

>>> def a(a):
...     for k,v in sys._getframe(1).f_locals.items():
...         if id(v) == id(a):
...             print k
...

>>> hello = 123

>>> a(hello)
hello

## pretty cool.


It's totally useless but I wanted to do it for logging purposes.  It
will still return weird results if you have two labels pointing to the
same object but I'm not sure how to get around that, any ideas?

Regards,
Ravi Kotecha



More information about the Python-list mailing list