Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to pass argument name using variable

A module I'm using has many functions defined with different argument names more or less serving the same purpose:

def func1(start_date):
    ....
def func2(startdate):
    ....
def func3(s_date):
    ....
def func4(sdate):
    ....

and they appear all in different positions of the argument list (in the above simplified case they're all in position 1, but in reality that's not the case).

I want to write a wrapper that can pass the actual start_date to any of these functions via a dictionary from function name to argument name:

def func2arg_name():
    return {'func1' : 'start_date', 
            'func2' : 'startdate', 
            'func3' : 's_date', 
            'func4' : 'sdate' }

Then the actual wrapper:

f2a = func2arg_name()
def func(func_name, sdate):
    locals()[func_name](f2a[func_name] = sdate)

func('func1', '20170101')

Clearly this doesn't work. Essentially the f2a[func_name] is not being recognized as a legit keyword. Does any one know how to do this, i.e. pass the argument name using a variable? Note func1 to func4 are externally defined and cannot be changed.

like image 666
Zhang18 Avatar asked Mar 16 '17 21:03

Zhang18


1 Answers

Make a dict with the argument name as the key, and pass it using unpack operator:

locals()[func_name](**{f2a[func_name]: sdate})

See Unpacking argument lists in the Python tutorial.

like image 183
David Röthlisberger Avatar answered Nov 15 '22 08:11

David Röthlisberger