Function that knows its argument's variable name

Gary Herron gherron at islandtraining.com
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:
  someMagic(42)
  someMagic(40+2)
  someMagic(f(123))
  someMagic(*argTuple)
  someMagic(**kwDict)
  someMagic(array[42])
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