In Python, get the argument passed to a function as a string within the function
Question: 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](http://stackoverflow.com/questions/582056/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?


Answer: 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'
    

