Function that knows its argument's variable name

Tino Wildenhain tino at wildenhain.de
Wed Mar 17 02:30:36 EDT 2010


Hi,

Am 14.03.2010 12:58, schrieb Helge Stenström:
> 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?

apart from very hackery, why don't you just use:

def probe(**vars):
     for varname,value in vars.items():
         print "%s = %r" % (varname,value)

and call it like that:

probe(myvar="foo")
probe(othervar="bar")

or even

probe(myvar=myvar) (if myvar was assigned before)

please note introspective approaches have a very narrow field
where they can work - as already shown in other posts: you can have
values w/o names and also more then one name to a value (or object).

Regards
Tino Wildenhain

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 3254 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100317/fe37b83a/attachment-0001.bin>


More information about the Python-list mailing list