william007
william007

Reputation: 18525

Get the name of a python variable

def f(s)
  print <name of s> = s

I wish to output "hello=10" for f(hello), given that the variable hello has value 10.

The problem is how to get the variable name of the variable, i.e., <name of s>?

This is for debugging purpose. Say given a new statement s=2

f(s) before the new statement will print s=0 if s is initially 0, f(s) after the new statement will print s=2.

I can easily write:

def f(name,value)
   print "%s=%s"%(name,str(value))

and use it as f("s",s), but that would need me to input two arguments, which is more cumbersome.

Upvotes: 0

Views: 823

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

I am not sure if it is actually worth it, but using the information from frames for simple function calls with positional arguments you can do something like this:

import inspect

def hello(s1, s2, s3, s4):
    args = inspect.getargspec(hello).args
    line = inspect.getouterframes(inspect.currentframe())[1][4][0]
    actual_args = map(str.strip, line[line.index('(')+1: line.index(')')].split(','))
    for x, y in zip(args, actual_args):
        print "value of {} is {}".format(y, locals()[x])

a, b, c, d = 1, 2, 3, 4
hello(a, b, c, d)

output:

value of a is 1
value of b is 2
value of c is 3
value of d is 4

Upvotes: 7

Hannes Ovr&#233;n
Hannes Ovr&#233;n

Reputation: 21831

You could (probably) do this using the traceback module.

import traceback
def some_func(x):
    stack = traceback.extract_stack()
    calling = stack[-2]
    func_call_str = calling[-1]
    print func_call_str

There are probably lots of caveats that I'm unaware of, but at least calling some_func(hello) should print some_func(hello) and you can just proceed and extract the "variable name" using string extraction methods.

Upvotes: 3

Haridas N
Haridas N

Reputation: 549

If you have only one argument there for the function; then you can do this way.

def f(s):
    var, val = locals.items()[0]  # `var` will always have value 's', so no much difference here.
    print "{} = {}".format(var, val)

In your case the passing argument ( Actual parameter ) name won't be available once it passed in to the function ( Formal parameter ).

Upvotes: -1

okainov
okainov

Reputation: 4654

You can do it this way:

def func(**kwargs):
    for key in kwargs:
        print 'Var <%s> with value <%s>' % (key, kwargs[key])

>>> func(say=2, qqq=3)
    Var <say> with value <2>
    Var <qqq> with value <3>

Upvotes: -2

Related Questions