Function that knows its argument's variable name

Gary Herron gherron at
Sun Mar 14 17:45:51 CET 2010

Helge Stenström wrote:
> I want to write  function that prints a value of a variable, for
> debugging. Like:
> with
> myVariable = "parrot"
> otherVariable = "dead"
> probe(myVariable)
> probe(otherVariable)
> instead of the longer
> print "myVariable = ", myVariable
> print "otherVariable = ", otherVariable
> Is that even possible?
> The function would look like
> def probe(var):
>     nameOfVar = someMagic(var)
>     print nameOfVar, " = ", var
> but can someMagic(var) find the variable name? Is that possible?

That question really doesn't  quite make sense.    Consider all the 
ways  such a function can be called:
None of which have a variable name associated with the argument.

Yet, the answer to your question is not quite absolutely "no".  Python 
has lots of introspection capabilities, including, perhaps, getting at 
and parsing the original code to find the call.    But there's nothing 
direct for what you want.

Gary Herron


More information about the Python-list mailing list