Getting the name of a variable which was used as a functionparameter.

R

Ravi Kotecha

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.
.... for k,v in sys._getframe(1).f_locals.items():
.... if id(v) == id(a):
.... print k
....
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
 
M

Marc 'BlackJack' Rintsch

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.

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

hello

## pretty cool.

Or ugly hack. Beauty lies in the eye of the beer holder…
It's totally useless but I wanted to do it for logging purposes.

Don't use such things in production code, please.

Ciao,
Marc 'BlackJack' Rintsch
 
R

Ravi Kotecha

Of course I wouldn't, it is a total hack, mostly useless but fun. I
tried to do it after someone in #python efnet said it was impossible!
 
F

Fredrik Lundh

Ravi said:
Of course I wouldn't, it is a total hack, mostly useless but fun. I
tried to do it after someone in #python efnet said it was impossible!

your function only finds *some* name (if it finds a name at all), not
*the* name, so you haven't really proven that someone wrong yet.

you can get a lot closer by using more radical approaches, but I don't
think it's possible to do this in a fully robust way, at least not from
the Python level.

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top