1

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?

Community
  • 1
  • 1
Kurt Peek
  • 52,165
  • 91
  • 301
  • 526
  • Could you possibly elaborate a little more as to what you're trying to achieve? If you're looking for something that simply echoes the values of its arguments you could just return them. If you want to know the names of their variables (i.e. arg1, arg2) then what you are doing is correct. Not sure as to what your desired output is. – Bob Jul 07 '14 at 16:31
  • `arg_1 = args.locals["arg1"]` will return the variable value – Padraic Cunningham Jul 07 '14 at 16:34

3 Answers3

2

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'
D Krueger
  • 2,446
  • 15
  • 12
1

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')]
tharen
  • 1,262
  • 10
  • 22
0

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'
Chris Clarke
  • 2,103
  • 2
  • 14
  • 19