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?

5
  • 2
    write2db(*myargs) Commented Jan 16, 2017 at 22:29
  • 1
    Possible duplicate of How to extract parameters from a list and pass them to a function call Commented Jan 16, 2017 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. Commented Jan 16, 2017 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? Commented Jan 16, 2017 at 22:52
  • Sorry and you don't need to shout on a beginner :) Commented Jan 16, 2017 at 22:56

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

So you think args = [int(pocnr), larm1, tid, label1, q1, x, y, lat, long, radio] will do the trick?
It did! Thanks alot. Now i can make my code more clean and easier to admin.
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

1 Comment

You can just pass f(*args). No need to change any definitions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.