Question

So I'm really not sure how to word this question, or I'm sure I could just google it.

I have a function such as:

def example(parameter1 = "", parameter2 = "", parameter3 =""):
    print(parameter1)
    print(parameter2)
    print(parameter3)

And I want to be able to, say, call it 3 times and pass in only one parameter at once such as:

example(parameter1 = "Hello")
example(parameter2 = "Stack")
example(parameter3 = "Overflow")

But in my real code I need to generalize this heavily and have a LOT more parameters, so I want to be able to do something along the lines of:

paramnames = ['parameter1', 'parameter2', 'parameter3']
parameters = ['Hello', 'Stack', 'Overflow']

for i in range(3):
    example(paramnames[i] = parameters[i])

Is there any way in python to accomplish this?

Was it helpful?

Solution

What you're looking for is called argument packing, and uses * or ** to denote positional and named arguments:

paramnames = ['parameter1', 'parameter2', 'parameter3']
parameters = ['Hello', 'Stack', 'Overflow']

for name, value in zip(paramnames, parameters):
    example(**{name: value})

def example(parameter1="", parameter2="", parameter3=""):
    print(parameter1)
    print(parameter2)
    print(parameter3)

Keep in mind that if an argument isn't passed, it'll be the default. So the output is:

Hello



Stack



Overflow

OTHER TIPS

Use a dict and the ** notation:

parameters = {'parameter1': 'Hello',
              'parameter2': 'Stack', 
              'parameter3': 'Overflow'}

for k, v in parameters.items():
    example(**{k: v})

If you need to retain order, use an OrderedDict

why not using a dict like that :

paramnames = ['parameter1', 'parameter2', 'parameter3']
parameters = ['Hello', 'Stack', 'Overflow']

for i in range(3):
    example({paramnames[i] : parameters[i]})

and :

def example(para_dict):
    for k,v in para_dict.items():
        print(v)

if you want to use every parameter on deffrent code you can testing on "k"

There are a few ways you can do this.

The most straight forward way is probably to use a dictionary to hold the arguments before you pass them all to the function using example(**param_dict).

A more "fancy" approach would be to use functools.partial to a callable object with some parameters prespecified. You'd do something like example = partial(example, parameter1="hello") to add parameters, then just call example() at the end. This approach could be useful if the parameters come from many different places and you need to keep the function with its parameters around for a while, like in a callback.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top