Fallen Apart
Fallen Apart

Reputation: 741

Can I pass the name of a parameter as an argument?

Let say I have a function F with two optional parameters par1 and par2.

I want to write a new function:

def some_plot(parameter):
    array = []
    for n in range(100):
        array.append(F(parameter = n))
    # make some plot using array

And then I want to make some plot by calling some_plot('par1') (or some_plot(par1)) which both split errors.

Is it possible to pass the name of the parameter as an argument?

Upvotes: 0

Views: 71

Answers (2)

Thierry Lathuille
Thierry Lathuille

Reputation: 24288

Supposing that you pass the name of the argument as a string, you can use keyword argument expansion:

def loop_through(parameter):

    for n in range(100):
        kwargs = {parameter: n}
        F(**kwargs)

Upvotes: 5

kindall
kindall

Reputation: 184395

You can do this by constructing a dictionary and passing it using the ** syntax.

def loop_through(arg_name):
    for n in range(100):
        F(**{arg_name: n})

Upvotes: 6

Related Questions