6

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.

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.