Search code examples
pythonparametersexpressionkeywordgeneralization

refer to specific parameter by object in array?


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?


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