1

Given a set of functions that differ in their signatures and a dictionary that contains (key, value) pairs for each of the required arguments, I want to find an elegant way of passing the dictionary to each function, so that each function may use the parameters from the function it requires.

def first_function(name, age):
    print(name, " ", age)

def second_function(name, gender):
    print(name, " ", gender)

param_dict = {'name': 'Max', 'age': 23, 'gender':'m'}

Passing the param_dict to the function by specifying second_function(**param_dict) throws an error as neither function requires for all three parameters. Is there an elegant solution, such that each functions 'extracts' the parameters it requires?

1 Answer 1

6

You can simply pass **kwargs as a third arg to get around this problem, since it will consume what it needs out of the dictionary, the rest will remain collected in the kwargs dict:

def first_function(name, age, **kwargs):
    print(name, age)

def second_function(name, gender, **kwargs):
    print(name, gender)

param_dict = {'name': 'Max', 'age': 23, 'gender':'m'}

first_function(**param_dict)
# Max 23

second_function(**param_dict)
# Max m
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.