Function that knows its argument's variable name

Gregory Ewing greg.ewing at canterbury.ac.nz
Wed Mar 17 00:32:40 CET 2010


Helge Stenström wrote:

> I want to write  function that prints a value of a variable, for
> debugging. Like:
> 
> myVariable = "parrot"
> otherVariable = "dead"
 >
> probe(myVariable)
> probe(otherVariable)

Not exactly, but you can come close with a little hackery.

import sys

def print_var(name):
   print name, "=", sys._getframe(1).f_locals[name]

def f():
   fred = 42
   mary = "christmas"
   print_var("fred")
   print_var("mary")

f()

-- 
Greg



More information about the Python-list mailing list