Calling Python function with set of parameters from variable - python

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?

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)

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

Related

kargs and args behaving strange

I was just testing a piece of code with kwargs and args. But why args is picking up all the passed parameters in the following code ?
def myfunc(color='red',*args,**kwargs):
print (args)
print (color)
print (kwargs)
names=["Ramesh","Krishna"]
ages={'Ramesh_age':20,'Krishna_age':10,'Kanchi_age':5}
myfunc('blue',names,ages)
Result:
(['Ramesh', 'Krishna'], {'Krishna_age': 10, 'Ramesh_age': 20, 'Kanchi_age': 5})
blue
{}
why it all including ages has been assigned to ages and kwargs is empty ?
You need to use *names to unwrap names and **ages to unwrap ages.
Like this myfunc('blue', *names, **ages)
To be precise, kwargs is not picking up any values because kwargs looks for key - value pairs.
The way you passed your arguements, there is no key value pairs. You passed along
ages={'Ramesh_age':20,'Krishna_age':10,'Kanchi_age':5}
as a whole object, instead of destructuring the object and passing it as individual key value pairs.
As others have pointed out, the correct way is to destructure the object as seperate key value pairs as:
**ages
args looks for any values and kwargs looks for any key-value pairs. When you call your function, you have to specify * before args and ** before kwargs. It is the way Python works.
Here's your code:
def myfunc(color='red',*args,**kwargs):
print (args)
print (color)
print (kwargs)
names=["Ramesh","Krishna"]
ages={'Ramesh_age':20,'Krishna_age':10,'Kanchi_age':5}
# to call the function
myfunc('blue', *names, **ages)
Here's the results:
('Ramesh', 'Krishna')
blue
{'Ramesh_age': 20, 'Krishna_age': 10, 'Kanchi_age': 5}
Explanations can be found here and here

How to store user input as a keyword argument in python [duplicate]

This question already has answers here:
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
(25 answers)
Closed 9 years ago.
So I have difficulty with the concept of *args and **kwargs.
So far I have learned that:
*args = list of arguments - as positional arguments
**kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.
I don't understand what programming task this would be helpful for.
Maybe:
I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument?
Is there a simple example to explain how *args and **kwargs are used?
Also the tutorial I found used just the "*" and a variable name.
Are *args and **kwargs just placeholders or do you use exactly *args and **kwargs in the code?
The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them.
You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:
>>> def print_everything(*args):
for count, thing in enumerate(args):
... print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage
Similarly, **kwargs allows you to handle named arguments that you have not defined in advance:
>>> def table_things(**kwargs):
... for name, value in kwargs.items():
... print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit
You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and **kwargs. The named arguments come first in the list. For example:
def table_things(titlestring, **kwargs)
You can also use both in the same function definition but *args must occur before **kwargs.
You can also use the * and ** syntax when calling a function. For example:
>>> def print_three_things(a, b, c):
... print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat
As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call.
One place where the use of *args and **kwargs is quite useful is for subclassing.
class Foo(object):
def __init__(self, value1, value2):
# do something with the values
print value1, value2
class MyFoo(Foo):
def __init__(self, *args, **kwargs):
# do something else, don't care about the args
print 'myfoo'
super(MyFoo, self).__init__(*args, **kwargs)
This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class.
Here's an example that uses 3 different types of parameters.
def func(required_arg, *args, **kwargs):
# required_arg is a positional-only parameter.
print required_arg
# args is a tuple of positional arguments,
# because the parameter name has * prepended.
if args: # If args is not empty.
print args
# kwargs is a dictionary of keyword arguments,
# because the parameter name has ** prepended.
if kwargs: # If kwargs is not empty.
print kwargs
>>> func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes at least 1 argument (0 given)
>>> func("required argument")
required argument
>>> func("required argument", 1, 2, '3')
required argument
(1, 2, '3')
>>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")
required argument
(1, 2, '3')
{'keyword2': 'foo', 'keyword1': 4}
Here's one of my favorite places to use the ** syntax as in Dave Webb's final example:
mynum = 1000
mystr = 'Hello World!'
print("{mystr} New-style formatting is {mynum}x more fun!".format(**locals()))
I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!
One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped:
def mydecorator( f ):
#functools.wraps( f )
def wrapper( *args, **kwargs ):
print "Calling f", args, kwargs
v = f( *args, **kwargs )
print "f returned", v
return v
return wrapper
*args and **kwargs are special-magic features of Python.
Think of a function that could have an unknown number of arguments. For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). So you write this function:
def sumFunction(*args):
result = 0
for x in args:
result += x
return result
and use it like: sumFunction(3,4,6,3,6,8,9).
**kwargs has a diffrent function. With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary.
def someFunction(**kwargs):
if 'text' in kwargs:
print kwargs['text']
Calling someFunction(text="foo") will print foo.
Just imagine you have a function but you don't want to restrict the number of parameter it takes.
Example:
>>> import operator
>>> def multiply(*args):
... return reduce(operator.mul, args)
Then you use this function like:
>>> multiply(1,2,3)
6
or
>>> numbers = [1,2,3]
>>> multiply(*numbers)
6
The names *args and **kwargs or **kw are purely by convention. It makes it easier for us to read each other's code
One place it is handy is when using the struct module
struct.unpack() returns a tuple whereas struct.pack() uses a variable number of arguments. When manipulating data it is convenient to be able to pass a tuple to struck.pack() eg.
tuple_of_data = struct.unpack(format_str, data)
# ... manipulate the data
new_data = struct.pack(format_str, *tuple_of_data)
without this ability you would be forced to write
new_data = struct.pack(format_str, tuple_of_data[0], tuple_of_data[1], tuple_of_data[2],...)
which also means the if the format_str changes and the size of the tuple changes, I'll have to go back and edit that really long line
Note that *args/**kwargs is part of function-calling syntax, and not really an operator. This has a particular side effect that I ran into, which is that you can't use *args expansion with the print statement, since print is not a function.
This seems reasonable:
def myprint(*args):
print *args
Unfortunately it doesn't compile (syntax error).
This compiles:
def myprint(*args):
print args
But prints the arguments as a tuple, which isn't what we want.
This is the solution I settled on:
def myprint(*args):
for arg in args:
print arg,
print
These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function.
def foo(bar=2, baz=5):
print bar, baz
def proxy(x, *args, **kwargs): # reqire parameter x and accept any number of additional arguments
print x
foo(*args, **kwargs) # applies the "non-x" parameter to foo
proxy(23, 5, baz='foo') # calls foo with bar=5 and baz=foo
proxy(6)# calls foo with its default arguments
proxy(7, bar='asdas') # calls foo with bar='asdas' and leave baz default argument
But since these parameters hide the actual parameter names, it is better to avoid them.
You can have a look at python docs (docs.python.org in the FAQ), but more specifically for a good explanation the mysterious miss args and mister kwargs (courtesy of archive.org) (the original, dead link is here).
In a nutshell, both are used when optional parameters to a function or method are used.
As Dave says, *args is used when you don't know how many arguments may be passed, and **kwargs when you want to handle parameters specified by name and value as in:
myfunction(myarg=1)

Difference between python's parameters '*', '*args', '**', '**kwargs' [duplicate]

This question already has answers here:
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
(25 answers)
Closed 9 years ago.
So I have difficulty with the concept of *args and **kwargs.
So far I have learned that:
*args = list of arguments - as positional arguments
**kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.
I don't understand what programming task this would be helpful for.
Maybe:
I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument?
Is there a simple example to explain how *args and **kwargs are used?
Also the tutorial I found used just the "*" and a variable name.
Are *args and **kwargs just placeholders or do you use exactly *args and **kwargs in the code?
The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them.
You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:
>>> def print_everything(*args):
for count, thing in enumerate(args):
... print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage
Similarly, **kwargs allows you to handle named arguments that you have not defined in advance:
>>> def table_things(**kwargs):
... for name, value in kwargs.items():
... print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit
You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and **kwargs. The named arguments come first in the list. For example:
def table_things(titlestring, **kwargs)
You can also use both in the same function definition but *args must occur before **kwargs.
You can also use the * and ** syntax when calling a function. For example:
>>> def print_three_things(a, b, c):
... print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat
As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call.
One place where the use of *args and **kwargs is quite useful is for subclassing.
class Foo(object):
def __init__(self, value1, value2):
# do something with the values
print value1, value2
class MyFoo(Foo):
def __init__(self, *args, **kwargs):
# do something else, don't care about the args
print 'myfoo'
super(MyFoo, self).__init__(*args, **kwargs)
This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class.
Here's an example that uses 3 different types of parameters.
def func(required_arg, *args, **kwargs):
# required_arg is a positional-only parameter.
print required_arg
# args is a tuple of positional arguments,
# because the parameter name has * prepended.
if args: # If args is not empty.
print args
# kwargs is a dictionary of keyword arguments,
# because the parameter name has ** prepended.
if kwargs: # If kwargs is not empty.
print kwargs
>>> func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes at least 1 argument (0 given)
>>> func("required argument")
required argument
>>> func("required argument", 1, 2, '3')
required argument
(1, 2, '3')
>>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")
required argument
(1, 2, '3')
{'keyword2': 'foo', 'keyword1': 4}
Here's one of my favorite places to use the ** syntax as in Dave Webb's final example:
mynum = 1000
mystr = 'Hello World!'
print("{mystr} New-style formatting is {mynum}x more fun!".format(**locals()))
I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!
One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped:
def mydecorator( f ):
#functools.wraps( f )
def wrapper( *args, **kwargs ):
print "Calling f", args, kwargs
v = f( *args, **kwargs )
print "f returned", v
return v
return wrapper
*args and **kwargs are special-magic features of Python.
Think of a function that could have an unknown number of arguments. For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). So you write this function:
def sumFunction(*args):
result = 0
for x in args:
result += x
return result
and use it like: sumFunction(3,4,6,3,6,8,9).
**kwargs has a diffrent function. With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary.
def someFunction(**kwargs):
if 'text' in kwargs:
print kwargs['text']
Calling someFunction(text="foo") will print foo.
Just imagine you have a function but you don't want to restrict the number of parameter it takes.
Example:
>>> import operator
>>> def multiply(*args):
... return reduce(operator.mul, args)
Then you use this function like:
>>> multiply(1,2,3)
6
or
>>> numbers = [1,2,3]
>>> multiply(*numbers)
6
The names *args and **kwargs or **kw are purely by convention. It makes it easier for us to read each other's code
One place it is handy is when using the struct module
struct.unpack() returns a tuple whereas struct.pack() uses a variable number of arguments. When manipulating data it is convenient to be able to pass a tuple to struck.pack() eg.
tuple_of_data = struct.unpack(format_str, data)
# ... manipulate the data
new_data = struct.pack(format_str, *tuple_of_data)
without this ability you would be forced to write
new_data = struct.pack(format_str, tuple_of_data[0], tuple_of_data[1], tuple_of_data[2],...)
which also means the if the format_str changes and the size of the tuple changes, I'll have to go back and edit that really long line
Note that *args/**kwargs is part of function-calling syntax, and not really an operator. This has a particular side effect that I ran into, which is that you can't use *args expansion with the print statement, since print is not a function.
This seems reasonable:
def myprint(*args):
print *args
Unfortunately it doesn't compile (syntax error).
This compiles:
def myprint(*args):
print args
But prints the arguments as a tuple, which isn't what we want.
This is the solution I settled on:
def myprint(*args):
for arg in args:
print arg,
print
These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function.
def foo(bar=2, baz=5):
print bar, baz
def proxy(x, *args, **kwargs): # reqire parameter x and accept any number of additional arguments
print x
foo(*args, **kwargs) # applies the "non-x" parameter to foo
proxy(23, 5, baz='foo') # calls foo with bar=5 and baz=foo
proxy(6)# calls foo with its default arguments
proxy(7, bar='asdas') # calls foo with bar='asdas' and leave baz default argument
But since these parameters hide the actual parameter names, it is better to avoid them.
You can have a look at python docs (docs.python.org in the FAQ), but more specifically for a good explanation the mysterious miss args and mister kwargs (courtesy of archive.org) (the original, dead link is here).
In a nutshell, both are used when optional parameters to a function or method are used.
As Dave says, *args is used when you don't know how many arguments may be passed, and **kwargs when you want to handle parameters specified by name and value as in:
myfunction(myarg=1)

pass **kwargs argument to another function with **kwargs

I do not understand the following example, let's say I have these functions:
# python likes
def save(filename, data, **kwargs):
fo = openX(filename, "w", **kwargs) # <- #1
fo.write(data)
fo.close()
# python doesnt like
def save2(filename, data, **kwargs):
fo = openX(filename, "w", kwargs) # <- #2
fo.write(data)
fo.close()
def openX(filename, mode, **kwargs):
#doing something fancy and returning a file object
Why is #1 the right solution and #2 the wrong one? **kwargs is basically a dict, so if I want to pass down the argument to openX I think the correct way would be without ** and just giving the dict. But Python obviously doesn't like the second one and tells me I gave 3 instead of 2 arguments.
So what's the reason behind this?
In the second example you provide 3 arguments: filename, mode and a dictionary (kwargs). But Python expects: 2 formal arguments plus keyword arguments.
By prefixing the dictionary by '**' you unpack the dictionary kwargs to keywords arguments.
A dictionary (type dict) is a single variable containing key-value pairs.
"Keyword arguments" are key-value method-parameters.
Any dictionary can by unpacked to keyword arguments by prefixing it with ** during function call.
Expanding on #gecco 's answer, the following is an example that'll show you the difference:
def foo(**kwargs):
for entry in kwargs.items():
print("Key: {}, value: {}".format(entry[0], entry[1]))
# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})
# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")
Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails
The ** syntax tells Python to collect keyword arguments into a dictionary. The save2 is passing it down as a non-keyword argument (a dictionary object). The openX is not seeing any keyword arguments so the **args doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX function.
def openX(filename, mode, kwargs):
pass
For #2
args will be only a formal parameter with dict value, but not a keyword type parameter.
If you want to pass a keyword type parameter into a keyword argument
You need to specific ** before your dictionary, which means **args
check this out for more detail on using **kw
http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
Because a dictionary is a single value. You need to use keyword expansion if you want to pass it as a group of keyword arguments.
The following code use kwargs and transfer it to another function:
def myprint( kwargs ):
# default values
a = kwargs.get('a', None)
b = kwargs.get('b', None)
# print both
print('a={}, b={}'.format(a,b))
def mytest( **kwargs ):
myprint( kwargs )
mytest()
mytest(b=2)
yields:
a=None, b=None
a=None, b=2

Use of *args and **kwargs [duplicate]

This question already has answers here:
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
(25 answers)
Closed 9 years ago.
So I have difficulty with the concept of *args and **kwargs.
So far I have learned that:
*args = list of arguments - as positional arguments
**kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.
I don't understand what programming task this would be helpful for.
Maybe:
I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument?
Is there a simple example to explain how *args and **kwargs are used?
Also the tutorial I found used just the "*" and a variable name.
Are *args and **kwargs just placeholders or do you use exactly *args and **kwargs in the code?
The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them.
You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:
>>> def print_everything(*args):
for count, thing in enumerate(args):
... print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage
Similarly, **kwargs allows you to handle named arguments that you have not defined in advance:
>>> def table_things(**kwargs):
... for name, value in kwargs.items():
... print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit
You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and **kwargs. The named arguments come first in the list. For example:
def table_things(titlestring, **kwargs)
You can also use both in the same function definition but *args must occur before **kwargs.
You can also use the * and ** syntax when calling a function. For example:
>>> def print_three_things(a, b, c):
... print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat
As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call.
One place where the use of *args and **kwargs is quite useful is for subclassing.
class Foo(object):
def __init__(self, value1, value2):
# do something with the values
print value1, value2
class MyFoo(Foo):
def __init__(self, *args, **kwargs):
# do something else, don't care about the args
print 'myfoo'
super(MyFoo, self).__init__(*args, **kwargs)
This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class.
Here's an example that uses 3 different types of parameters.
def func(required_arg, *args, **kwargs):
# required_arg is a positional-only parameter.
print required_arg
# args is a tuple of positional arguments,
# because the parameter name has * prepended.
if args: # If args is not empty.
print args
# kwargs is a dictionary of keyword arguments,
# because the parameter name has ** prepended.
if kwargs: # If kwargs is not empty.
print kwargs
>>> func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes at least 1 argument (0 given)
>>> func("required argument")
required argument
>>> func("required argument", 1, 2, '3')
required argument
(1, 2, '3')
>>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")
required argument
(1, 2, '3')
{'keyword2': 'foo', 'keyword1': 4}
Here's one of my favorite places to use the ** syntax as in Dave Webb's final example:
mynum = 1000
mystr = 'Hello World!'
print("{mystr} New-style formatting is {mynum}x more fun!".format(**locals()))
I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!
One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped:
def mydecorator( f ):
#functools.wraps( f )
def wrapper( *args, **kwargs ):
print "Calling f", args, kwargs
v = f( *args, **kwargs )
print "f returned", v
return v
return wrapper
*args and **kwargs are special-magic features of Python.
Think of a function that could have an unknown number of arguments. For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). So you write this function:
def sumFunction(*args):
result = 0
for x in args:
result += x
return result
and use it like: sumFunction(3,4,6,3,6,8,9).
**kwargs has a diffrent function. With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary.
def someFunction(**kwargs):
if 'text' in kwargs:
print kwargs['text']
Calling someFunction(text="foo") will print foo.
Just imagine you have a function but you don't want to restrict the number of parameter it takes.
Example:
>>> import operator
>>> def multiply(*args):
... return reduce(operator.mul, args)
Then you use this function like:
>>> multiply(1,2,3)
6
or
>>> numbers = [1,2,3]
>>> multiply(*numbers)
6
The names *args and **kwargs or **kw are purely by convention. It makes it easier for us to read each other's code
One place it is handy is when using the struct module
struct.unpack() returns a tuple whereas struct.pack() uses a variable number of arguments. When manipulating data it is convenient to be able to pass a tuple to struck.pack() eg.
tuple_of_data = struct.unpack(format_str, data)
# ... manipulate the data
new_data = struct.pack(format_str, *tuple_of_data)
without this ability you would be forced to write
new_data = struct.pack(format_str, tuple_of_data[0], tuple_of_data[1], tuple_of_data[2],...)
which also means the if the format_str changes and the size of the tuple changes, I'll have to go back and edit that really long line
Note that *args/**kwargs is part of function-calling syntax, and not really an operator. This has a particular side effect that I ran into, which is that you can't use *args expansion with the print statement, since print is not a function.
This seems reasonable:
def myprint(*args):
print *args
Unfortunately it doesn't compile (syntax error).
This compiles:
def myprint(*args):
print args
But prints the arguments as a tuple, which isn't what we want.
This is the solution I settled on:
def myprint(*args):
for arg in args:
print arg,
print
These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function.
def foo(bar=2, baz=5):
print bar, baz
def proxy(x, *args, **kwargs): # reqire parameter x and accept any number of additional arguments
print x
foo(*args, **kwargs) # applies the "non-x" parameter to foo
proxy(23, 5, baz='foo') # calls foo with bar=5 and baz=foo
proxy(6)# calls foo with its default arguments
proxy(7, bar='asdas') # calls foo with bar='asdas' and leave baz default argument
But since these parameters hide the actual parameter names, it is better to avoid them.
You can have a look at python docs (docs.python.org in the FAQ), but more specifically for a good explanation the mysterious miss args and mister kwargs (courtesy of archive.org) (the original, dead link is here).
In a nutshell, both are used when optional parameters to a function or method are used.
As Dave says, *args is used when you don't know how many arguments may be passed, and **kwargs when you want to handle parameters specified by name and value as in:
myfunction(myarg=1)

Categories