2

I'm sorry if the question is a bit unclear, I'm not sure how to phrase it.

I'm working with a package that has a function with a number of optional parameters. Say there are three parameters: x, y, z. I will always pass the same value, just to a different parameter. So I could do this:

if setting is x:
    package.someFunction(x=1)
elif setting is y:
    package.someFunction(y=1)
elif setting is z:
    package.someFunction(z=1)

Is there a more pythonic way to do it? Can I assign the parameter name to some variable pass it that way?

1 Answer 1

5

I would build a dictionary with setting as the key and the static value as the value. This way, you don't have to do that awkward switching.

For example:

setting = 'x'
kwargs = {setting: 1}
package.someFunction(**kwargs)

Just change the setting = 'x' line to be however you're getting that setting. It just needs to equal the name of the argument in package.someFunction that you want to apply the value to.

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

4 Comments

So setting would just be 'x' or 'z'? That's great, thanks!
@Niel Exactly. You'd have setting be a string with the name of the argument.
You don't even need the variable for the argument; you can pass a dict literal: package.someFunction(**{setting: 1}).
@chepner Yeah, normally that's how I'd do it. I'm just breaking it down to make each step clearer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.