2

I have a function

def input_definition(parameter_variation=None):

    input_def = {}
    input_def['a'] = 1
    input_def['b'] = 2
    input_def['c'] = 3
    ...
    input_def['z'] = 26

    # Apply the parameter variation by means of the input argument 'parameter_variation'.
    # ...

    # Save 'input_def' to external file with dill module.
    # ...

with many parameters. I want to vary some of these parameters by giving parameter_variation to the function input_definition. I need to vary different parameters each time I call input_definition.

So one time parameter_variation contains values for a and b and another time parameter_variation contains values for c and d.

What is the best / most neat / Pythonic way to do this? Or is it perhaps better to use kwargs?

0

1 Answer 1

4

You can use kwargs for this like so:

def some_func(**kwargs):
    my_dict = dict(
        a=1,
        b=2,
        c=3,
        d=4
    )
    my_dict.update(**kwargs)

This will set your defaults and then override them with kwargs.

It is arguable better to give more limited inputs to the dict by simply using default arguments like so:

def some_func(a=1, b=2, c=3, d=4):
    my_dict = dict(
        a=a,
        b=b,
        c=c,
        d=d
    )

This is more secure and makes your intentions more understandable to someone reading your code. But is less flexible in comparison to kwargs.

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

1 Comment

@Adriaan if this answered your question please mark it as the correct answer to help future people looking for the same issue :-).

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.