Function that knows its argument's variable name

Helge Stenström h.stenstrom at gmail.com
Wed Mar 17 14:20:42 CET 2010


Thank you to all who answered. Inspection is apparently possible, but
too complex for me.
Greg's solution does what I want, inserting "" is no problem.

/Helge


> 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