Kurt Peek
Kurt Peek

Reputation: 57471

In Python, get the argument passed to a function as a string within the function

I'm currently trying to access the arguments of a Python function as strings, because I would like to use these in a naming convention for the output of the function. To start off, I would first like to create a function which simply 'echoes' its arguments (cf. Getting list of parameter names inside python function). I tried this:

import inspect

def echo_arguments(arg1,arg2):
    frame = inspect.currentframe()
    args, _, _, _ = inspect.getargvalues(frame)
    arg1=args[0]
    arg2=args[1]
    return arg1, arg2

However, if I try to call it, I get this:

>>> (h1,h2)=echo_arguments('hello','world')
>>> h1
'arg1'
>>> h2
'arg2'

In other words, it is returning the 'dummy' arguments from when the function was defined, instead of the 'current' arguments at the time the function is called. Does anybody know how I could get the latter?

Upvotes: 1

Views: 3721

Answers (3)

Chris Clarke
Chris Clarke

Reputation: 2181

All you need to get the contents of those variables is the variables themselves

def echo_arguments(arg1, arg2):
    return arg1, arg2

>>> (h1, h2) = echo_arguments('hello', 'world')
>>> h1
'hello'
>>> h2
'world'

Upvotes: -1

tharen
tharen

Reputation: 1300

I would use the ArgInfo object that is returned by inspect.getargvalues(). It includes the argument names as well as the current values in the locals dict.

In [1]: import inspect

In [2]: def foo(a,b=None):
   ...:     frame = inspect.currentframe()
   ...:     args = inspect.getargvalues(frame)
   ...:     return args

In [3]: args = foo(1234,b='qwerty')

In [4]: print args
ArgInfo(args=['a', 'b'], varargs=None, keywords=None, locals={'a': 1234, 'frame': <frame object at 0x072F4198>, 'b': 'qwerty'})

In [5]: print [(arg,args.locals[arg]) for arg in args.args]
[('a', 1234), ('b', 'qwerty')]

Upvotes: 1

D Krueger
D Krueger

Reputation: 2476

Use the locals return by getargvalues:

import inspect

def echo_arguments(arg1,arg2):
    frame = inspect.currentframe()
    args, _, _, locals_ = inspect.getargvalues(frame)
    return (locals_[arg] for arg in args)

Results in:

>>> (h1,h2)=echo_arguments('hello','world')
>>> h1
'hello'
>>> h2
'world'

Upvotes: 2

Related Questions