0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    `write2db(*myargs)` – juanpa.arrivillaga Jan 16 '17 at 22:29
  • 1
    Possible duplicate of [How to extract parameters from a list and pass them to a function call](http://stackoverflow.com/questions/7527849/how-to-extract-parameters-from-a-list-and-pass-them-to-a-function-call) – juanpa.arrivillaga Jan 16 '17 at 22:30
  • i feel stupid but i dont understand all the answers. To clear the question a bit. How do I define the myargs? I've tried to do it global as myargs = (int(pocnr), larm1, tid, label1, q1, x, y, lat, long, radio) but then the variables are not defined yet. – Stefan Rydberg Jan 16 '17 at 22:51
  • There is an explicit example by denvaar. Also, **do not post code in comments. Why do you expect people to read your code in a comment, especially for python, where indentation is important?** – juanpa.arrivillaga Jan 16 '17 at 22:52
  • Sorry and you don't need to shout on a beginner :) – Stefan Rydberg Jan 16 '17 at 22:56

2 Answers2

2

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)
denvaar
  • 2,174
  • 2
  • 22
  • 26
0

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
Greg Jennings
  • 1,611
  • 16
  • 25