Stefan Rydberg
Stefan Rydberg

Reputation: 11

Calling Python function with set of parameters from variable

In my Python script I call this function a few times

write2db(int(pocnr), larm1, tid, label1, q1, x, y, lat, long, radio)

I want to be able to have the set of variables in one variable.

Should look like this

write2db(myargs)

So when I make a change to list of args I don't have to do it in more than one place. I have tried a few things but so far no luck. Any suggestions?

Upvotes: 0

Views: 145

Answers (2)

denvaar
denvaar

Reputation: 2214

You can use *args or **kwargs. The names args and kwargs don't actually matter, but its the * and ** that does the trick. Basically, * will unpack a list, and similarly, ** will unpack a dict.

*args is just a list of values in the same order as where you defined your function.

eg.

args = [23, 6, 2, "label", 5, 25, 21, 343.22, 111.34, 2]
write2db(*args)

**kwargs is a key-value mapping (python dict) of argument names to argument values

eg.

kwargs = {
    'pocnr': 23,
    'larm1': 21,
    # ... etc.
}
write2db(**kwargs)

Upvotes: 2

Greg Jennings
Greg Jennings

Reputation: 1641

You could create a namedtuple with each of those arguments, then get the arguments out by name inside of the function.

Or you could just use variable length argument *args, and then inside your function:

    for arg in args:
        # do something with arg

Upvotes: 0

Related Questions