What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
In the following method definitions, what does the *
and **
do for param2
?
def foo(param1, *param2):
def bar(param1, **param2):
python syntax parameter-passing identifier kwargs
add a comment |
In the following method definitions, what does the *
and **
do for param2
?
def foo(param1, *param2):
def bar(param1, **param2):
python syntax parameter-passing identifier kwargs
see also stackoverflow.com/questions/6967632/…
– Aaron Hall♦
Mar 1 '18 at 20:53
Related: Why use packed *args/**kwargs instead of passing list/dict?
– Steven M. Vascellaro
Mar 7 '18 at 21:26
More great insight: stackoverflow.com/a/11315061/4561887
– Gabriel Staples
Nov 16 '18 at 20:47
See also stackoverflow.com/questions/14301967/… for a bare asterisk
– naught101
Dec 13 '18 at 3:43
add a comment |
In the following method definitions, what does the *
and **
do for param2
?
def foo(param1, *param2):
def bar(param1, **param2):
python syntax parameter-passing identifier kwargs
In the following method definitions, what does the *
and **
do for param2
?
def foo(param1, *param2):
def bar(param1, **param2):
python syntax parameter-passing identifier kwargs
python syntax parameter-passing identifier kwargs
edited Sep 3 '17 at 11:57
Florian_1990
84
84
asked Aug 31 '08 at 15:04
Todd
9,94731813
9,94731813
see also stackoverflow.com/questions/6967632/…
– Aaron Hall♦
Mar 1 '18 at 20:53
Related: Why use packed *args/**kwargs instead of passing list/dict?
– Steven M. Vascellaro
Mar 7 '18 at 21:26
More great insight: stackoverflow.com/a/11315061/4561887
– Gabriel Staples
Nov 16 '18 at 20:47
See also stackoverflow.com/questions/14301967/… for a bare asterisk
– naught101
Dec 13 '18 at 3:43
add a comment |
see also stackoverflow.com/questions/6967632/…
– Aaron Hall♦
Mar 1 '18 at 20:53
Related: Why use packed *args/**kwargs instead of passing list/dict?
– Steven M. Vascellaro
Mar 7 '18 at 21:26
More great insight: stackoverflow.com/a/11315061/4561887
– Gabriel Staples
Nov 16 '18 at 20:47
See also stackoverflow.com/questions/14301967/… for a bare asterisk
– naught101
Dec 13 '18 at 3:43
see also stackoverflow.com/questions/6967632/…
– Aaron Hall♦
Mar 1 '18 at 20:53
see also stackoverflow.com/questions/6967632/…
– Aaron Hall♦
Mar 1 '18 at 20:53
Related: Why use packed *args/**kwargs instead of passing list/dict?
– Steven M. Vascellaro
Mar 7 '18 at 21:26
Related: Why use packed *args/**kwargs instead of passing list/dict?
– Steven M. Vascellaro
Mar 7 '18 at 21:26
More great insight: stackoverflow.com/a/11315061/4561887
– Gabriel Staples
Nov 16 '18 at 20:47
More great insight: stackoverflow.com/a/11315061/4561887
– Gabriel Staples
Nov 16 '18 at 20:47
See also stackoverflow.com/questions/14301967/… for a bare asterisk
– naught101
Dec 13 '18 at 3:43
See also stackoverflow.com/questions/14301967/… for a bare asterisk
– naught101
Dec 13 '18 at 3:43
add a comment |
18 Answers
18
active
oldest
votes
The *args
and **kwargs
is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
The *args
will give you all function parameters as a tuple:
In [1]: def foo(*args):
...: for a in args:
...: print a
...:
...:
In [2]: foo(1)
1
In [4]: foo(1,2,3)
1
2
3
The **kwargs
will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.
In [5]: def bar(**kwargs):
...: for a in kwargs:
...: print a, kwargs[a]
...:
...:
In [6]: bar(name='one', age=27)
age 27
name one
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs):
pass
Another usage of the *l
idiom is to unpack argument lists when calling a function.
In [9]: def foo(bar, lee):
...: print bar, lee
...:
...:
In [10]: l = [1,2]
In [11]: foo(*l)
1 2
In Python 3 it is possible to use *l
on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Also Python 3 adds new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
Such function accepts only 3 positional arguments, and everything after *
can only be passed as keyword arguments.
5
The output of [6] is in reverse order. name one age 27
– thanos.a
Jan 8 '17 at 21:11
23
@thanos.a Python dicts, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. "The order of elements in**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - docs.python.org/3/whatsnew/3.6.html In fact, all dicts in CPython 3.6 will remember insertion order, but this is an implementation detail for now, and users should not rely on it.
– Aaron Hall♦
Jan 12 '17 at 20:47
"The**kwargs
will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary." Do I understand correctly that formal parameters are complementary to keyword arguments, together making all inputs to a function?
– Post169
May 15 '18 at 21:59
5
Very precise, clean, and easy to understand. I appreciate that you noted that it's an "unpacking operator", so that I could differentiate from passing by reference in C. +1
– bballdave025
Jun 8 '18 at 0:56
add a comment |
It's also worth noting that you can use *
and **
when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
You can do things like:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
Note: The keys in mydict
have to be named exactly like the parameters of function foo
. Otherwise it will throw a TypeError
:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
add a comment |
The single * means that there can be any number of extra positional arguments. foo()
can be invoked like foo(1,2,3,4,5)
. In the body of foo() param2 is a sequence containing 2-5.
The double ** means there can be any number of extra named parameters. bar()
can be invoked like bar(1, a=2, b=3)
. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }
With the following code:
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
foo(1,2,3,4,5)
bar(1,a=2,b=3)
the output is
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
add a comment |
What does
**
(double star) and*
(star) do for parameters
They allow for functions to be defined to accept and for users to pass any number of arguments, positional (*
) and keyword (**
).
Defining Functions
*args
allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args
.
**kwargs
allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs
.
You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, args
and kwargs
are standard names.
Expansion, Passing any number of arguments
You can also use *args
and **kwargs
to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.
The function recieving the parameters does not have to know that they are being expanded.
For example, Python 2's xrange does not explicitly expect *args
, but since it takes 3 integers as arguments:
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
As another example, we can use dict expansion in str.format
:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
New in Python 3: Defining functions with keyword only arguments
You can have keyword only arguments after the *args
- for example, here, kwarg2
must be given as a keyword argument - not positionally:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
Usage:
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
Also, *
can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
Here, kwarg2
again must be an explicitly named, keyword argument:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
And we can no longer accept unlimited positional arguments because we don't have *args*
:
>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were given
Again, more simply, here we require kwarg
to be given by name, not positionally:
def bar(*, kwarg=None):
return kwarg
In this example, we see that if we try to pass kwarg
positionally, we get an error:
>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
We must explicitly pass the kwarg
parameter as a keyword argument.
>>> bar(kwarg='kwarg')
'kwarg'
Python 2 compatible demos
*args
(typically said "star-args") and **kwargs
(stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the *
and **
notation. These specific variable names aren't required (e.g. you could use *foos
and **bars
), but a departure from convention is likely to enrage your fellow Python coders.
We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).
Example 1
The following function describes how they can be used, and demonstrates behavior. Note the named b
argument will be consumed by the second positional argument before :
def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
# - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
# - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: n{0}'.format(
dict(**kwargs), kweg=kweg))
We can check the online help for the function's signature, with help(foo)
, which tells us
foo(a, b=10, *args, **kwargs)
Let's call this function with foo(1, 2, 3, 4, e=5, f=6, g=7)
which prints:
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
Example 2
We can also call it using another function, into which we just provide a
:
def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
bar(100)
prints:
a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
Example 3: practical usage in decorators
OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.
def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()
def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()
def baz(a, b, c, d, e, f):
... and so on
We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how *args
and **kwargs
can be very useful:
def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:
@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)
@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)
@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)
@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
And by factoring out our code, which *args
and **kwargs
allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.
add a comment |
Let us first understand what are positional arguments and keyword arguments.
Below is an example of function definition with Positional arguments.
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
So this is a function definition with positional arguments.
You can call it with keyword/named arguments as well:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
Now let us study an example of function definition with keyword arguments:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
You can call this function with positional arguments as well:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
So we now know function definitions with positional as well as keyword arguments.
Now let us study the '*' operator and '**' operator.
Please note these operators can be used in 2 areas:
a) function call
b) function definition
The use of '*' operator and '**' operator in function call.
Let us get straight to an example and then discuss it.
def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
print(a+b)
my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}
# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
# output is 3 in all three calls to sum function.
So remember
when the '*' or '**' operator is used in a function call -
'*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.
'**' operator unpacks a dictionary into arguments needed by function definition.
Now let us study the '*' operator use in function definition.
Example:
def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
sum = 0
for a in args:
sum+=a
print(sum)
sum(1,2,3,4) #positional args sent to function sum
#output:
10
In function definition the '*' operator packs the received arguments into a tuple.
Now let us see an example of '**' used in function definition:
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
sum=0
for k,v in args.items():
sum+=v
print(sum)
sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
In function definition The '**' operator packs the received arguments into a dictionary.
So remember:
In a function call the '*' unpacks data structure of tuple or list into positional or keyword arguments to be received by function definition.
In a function call the '**' unpacks data structure of dictionary into positional or keyword arguments to be received by function definition.
In a function definition the '*' packs positional arguments into a tuple.
In a function definition the '**' packs keyword arguments into a dictionary.
add a comment |
*
and **
have special usage in the function argument list. *
implies that the argument is a list and **
implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments
add a comment |
From the Python documentation:
If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax "*identifier" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).
If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax "**identifier" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.
add a comment |
For those of you who learn by examples!
- The purpose of
*
is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g.f(*myList)
). - The purpose of
**
is to give you the ability to feed a function's arguments by providing a dictionary (e.g.f(**{'x' : 1, 'y' : 2})
).
Let us show this by defining a function that takes two normal variables x
, y
, and can accept more arguments as myArgs
, and can accept even more arguments as myKW
. Later, we will show how to feed y
using myArgDict
.
def f(x, y, *myArgs, **myKW):
print("# x = {}".format(x))
print("# y = {}".format(y))
print("# myArgs = {}".format(myArgs))
print("# myKW = {}".format(myKW))
print("# ----------------------------------------------------------------------")
# Define a list for demonstration purposes
myList = ["Left", "Right", "Up", "Down"]
# Define a dictionary for demonstration purposes
myDict = {"Wubba": "lubba", "Dub": "dub"}
# Define a dictionary to feed y
myArgDict = {'y': "Why?", 'y0': "Why not?", "q": "Here is a cue!"}
# The 1st elem of myList feeds y
f("myEx", *myList, **myDict)
# x = myEx
# y = Left
# myArgs = ('Right', 'Up', 'Down')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# y is matched and fed first
# The rest of myArgDict becomes additional arguments feeding myKW
f("myEx", **myArgDict)
# x = myEx
# y = Why?
# myArgs = ()
# myKW = {'y0': 'Why not?', 'q': 'Here is a cue!'}
# ----------------------------------------------------------------------
# The rest of myArgDict becomes additional arguments feeding myArgs
f("myEx", *myArgDict)
# x = myEx
# y = y
# myArgs = ('y0', 'q')
# myKW = {}
# ----------------------------------------------------------------------
# Feed extra arguments manually and append even more from my list
f("myEx", 4, 42, 420, *myList, *myDict, **myDict)
# x = myEx
# y = 4
# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# Without the stars, the entire provided list and dict become x, and y:
f(myList, myDict)
# x = ['Left', 'Right', 'Up', 'Down']
# y = {'Wubba': 'lubba', 'Dub': 'dub'}
# myArgs = ()
# myKW = {}
# ----------------------------------------------------------------------
Caveats
**
is exclusively reserved for dictionaries.- Non-optional argument assignment happens first.
- You cannot use a non-optional argument twice.
- If applicable,
**
must come after*
, always.
add a comment |
While uses for the star/splat operators have been expanded in Python 3, I like the following table as it relates to use of these operators with functions. The splat operator(s) can be used both within function construction and in the function call:
In function *construction* In function *call*
=======================================================================
| def f(*args): | def f(a, b):
*args | for arg in args: | return a + b
| print(arg) | args = (1, 2)
| f(1, 2) | f(*args)
----------|--------------------------------|---------------------------
| def f(a, b): | def f(a, b):
**kwargs | return a + b | return a + b
| def g(**kwargs): | kwargs = dict(a=1, b=2)
| return f(**kwargs) | f(**kwargs)
| g(a=1, b=2) |
-----------------------------------------------------------------------
This really just serves to summarize Lorin Hochstein's answer but I find it helpful.
add a comment |
I want to give an example which others haven't mentioned
* can also unpack a generator
An example from Python3 Document
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
unzip_x will be [1, 2, 3], unzip_y will be [4, 5, 6]
The zip() receives multiple iretable args, and return a generator.
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
add a comment |
In Python 3.5, you can also use this syntax in list
, dict
, tuple
, and set
displays (also sometimes called literals). See PEP 488: Additional Unpacking Generalizations.
>>> (0, *range(1, 4), 5, *range(6, 8))
(0, 1, 2, 3, 5, 6, 7)
>>> [0, *range(1, 4), 5, *range(6, 8)]
[0, 1, 2, 3, 5, 6, 7]
>>> {0, *range(1, 4), 5, *range(6, 8)}
{0, 1, 2, 3, 5, 6, 7}
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> e = {'six': 6, 'seven': 7}
>>> {'zero': 0, **d, 'five': 5, **e}
{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
It also allows multiple iterables to be unpacked in a single function call.
>>> range(*[1, 10], *[2])
range(1, 10, 2)
(Thanks to mgilson for the PEP link.)
1
I'm not sure that this is a violation of "there's only one way to do it". There's no other way to initialize a list/tuple from multiple iterables -- You currently need to chain them into a single iterable which isn't always convenient. You can read about the rational in PEP-0448. Also, this isn't a python3.x feature, it's a python3.5+ feature :-).
– mgilson
Dec 8 '15 at 21:41
@mgilson, that would explain why it wasn't mentioned before.
– leewz
Dec 8 '15 at 22:23
add a comment |
In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write __init__
method in Python. Similar usage can seen in frameworks like Django code.
For example,
def __init__(self, *args, **kwargs):
for attribute_name, value in zip(self._expected_attributes, args):
setattr(self, attribute_name, value)
if kwargs.has_key(attribute_name):
kwargs.pop(attribute_name)
for attribute_name in kwargs.viewkeys():
setattr(self, attribute_name, kwargs[attribute_name])
A subclass can then be
class RetailItem(Item):
_expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']
class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['expiry_date']
The subclass then be instantiated as
food_item = FoodItem(name = 'Jam',
price = 12.0,
category = 'Foods',
country_of_origin = 'US',
expiry_date = datetime.datetime.now())
Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class __init__
to offload the attributes setting.
This is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,
class ElectronicAccessories(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['specifications']
# Depend on args and kwargs to populate the data as needed.
def __init__(self, specifications = None, *args, **kwargs):
self.specifications = specifications # Rest of attributes will make sense to parent class.
super(ElectronicAccessories, self).__init__(*args, **kwargs)
which can be instatiated as
usb_key = ElectronicAccessories(name = 'Sandisk',
price = '$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
The complete code is here
1
1. Basically init is a method, so (in this context) it's not really different. 2. Use # for comments, not """, which just marks literal strings. 3. Using super should be the preferred way, especially for your example with multi-level inheritance.
– 0xc0de
Feb 21 '18 at 8:24
add a comment |
A good example of using both in a function is:
>>> def foo(*arg,**kwargs):
... print arg
... print kwargs
>>>
>>> a = (1, 2, 3)
>>> b = {'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(*a,**b)
(1, 2, 3)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,**b)
((1, 2, 3),)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,b)
((1, 2, 3), {'aa': 11, 'bb': 22})
{}
>>>
>>>
>>> foo(a,*b)
((1, 2, 3), 'aa', 'bb')
{}
add a comment |
This example would help you remember *args
, **kwargs
and even super
and inheritance in Python at once.
class base(object):
def __init__(self, base_param):
self.base_param = base_param
class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1
add a comment |
*args
and **kwargs
: allow you to pass a variable number of arguments to a function.
*args
: is used to send a non-keyworded variable length argument list to the function:
def args(normal_arg, *argv):
print ("normal argument:",normal_arg)
for arg in argv:
print("Argument in list of arguments from *argv:", arg)
args('animals','fish','duck','bird')
Will produce:
normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird
**kwargs*
**kwargs
allows you to pass keyworded variable length of arguments to a function. You should use **kwargs
if you want to handle named arguments in a function.
def who(**kwargs):
if kwargs is not None:
for key, value in kwargs.items():
print ("Your %s is %s." %(key,value))
who (name="Nikola", last_name="Tesla", birthday = "7.10.1856", birthplace = "Croatia")
Will produce:
Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.
add a comment |
*
means receive variable arguments as list
**
means receive variable arguments as dictionary
Used like the following:
1) single *
def foo(*args):
for arg in args:
print(arg)
foo("two", 3)
Output:
two
3
2) Now **
def bar(**kwargs):
for key in kwargs:
print(key, kwargs[key])
bar(dic1="two", dic2=3)
Output:
dic1 two
dic2 3
add a comment |
def foo(param1, *param2):
is a method can accept arbitrary number of values for*param2
,
def bar(param1, **param2):
is a method can accept arbitrary number of values with keys for*param2
param1
is a simple parameter.
For example, the syntax for implementing varargs in Java as follows:
accessModifier methodName(datatype… arg) {
// method body
}
add a comment |
*args = *aList = all elements in a List
**args= ** aDict =all items in a dict
add a comment |
protected by Moinuddin Quadri Jan 22 '17 at 14:33
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
18 Answers
18
active
oldest
votes
18 Answers
18
active
oldest
votes
active
oldest
votes
active
oldest
votes
The *args
and **kwargs
is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
The *args
will give you all function parameters as a tuple:
In [1]: def foo(*args):
...: for a in args:
...: print a
...:
...:
In [2]: foo(1)
1
In [4]: foo(1,2,3)
1
2
3
The **kwargs
will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.
In [5]: def bar(**kwargs):
...: for a in kwargs:
...: print a, kwargs[a]
...:
...:
In [6]: bar(name='one', age=27)
age 27
name one
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs):
pass
Another usage of the *l
idiom is to unpack argument lists when calling a function.
In [9]: def foo(bar, lee):
...: print bar, lee
...:
...:
In [10]: l = [1,2]
In [11]: foo(*l)
1 2
In Python 3 it is possible to use *l
on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Also Python 3 adds new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
Such function accepts only 3 positional arguments, and everything after *
can only be passed as keyword arguments.
5
The output of [6] is in reverse order. name one age 27
– thanos.a
Jan 8 '17 at 21:11
23
@thanos.a Python dicts, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. "The order of elements in**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - docs.python.org/3/whatsnew/3.6.html In fact, all dicts in CPython 3.6 will remember insertion order, but this is an implementation detail for now, and users should not rely on it.
– Aaron Hall♦
Jan 12 '17 at 20:47
"The**kwargs
will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary." Do I understand correctly that formal parameters are complementary to keyword arguments, together making all inputs to a function?
– Post169
May 15 '18 at 21:59
5
Very precise, clean, and easy to understand. I appreciate that you noted that it's an "unpacking operator", so that I could differentiate from passing by reference in C. +1
– bballdave025
Jun 8 '18 at 0:56
add a comment |
The *args
and **kwargs
is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
The *args
will give you all function parameters as a tuple:
In [1]: def foo(*args):
...: for a in args:
...: print a
...:
...:
In [2]: foo(1)
1
In [4]: foo(1,2,3)
1
2
3
The **kwargs
will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.
In [5]: def bar(**kwargs):
...: for a in kwargs:
...: print a, kwargs[a]
...:
...:
In [6]: bar(name='one', age=27)
age 27
name one
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs):
pass
Another usage of the *l
idiom is to unpack argument lists when calling a function.
In [9]: def foo(bar, lee):
...: print bar, lee
...:
...:
In [10]: l = [1,2]
In [11]: foo(*l)
1 2
In Python 3 it is possible to use *l
on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Also Python 3 adds new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
Such function accepts only 3 positional arguments, and everything after *
can only be passed as keyword arguments.
5
The output of [6] is in reverse order. name one age 27
– thanos.a
Jan 8 '17 at 21:11
23
@thanos.a Python dicts, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. "The order of elements in**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - docs.python.org/3/whatsnew/3.6.html In fact, all dicts in CPython 3.6 will remember insertion order, but this is an implementation detail for now, and users should not rely on it.
– Aaron Hall♦
Jan 12 '17 at 20:47
"The**kwargs
will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary." Do I understand correctly that formal parameters are complementary to keyword arguments, together making all inputs to a function?
– Post169
May 15 '18 at 21:59
5
Very precise, clean, and easy to understand. I appreciate that you noted that it's an "unpacking operator", so that I could differentiate from passing by reference in C. +1
– bballdave025
Jun 8 '18 at 0:56
add a comment |
The *args
and **kwargs
is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
The *args
will give you all function parameters as a tuple:
In [1]: def foo(*args):
...: for a in args:
...: print a
...:
...:
In [2]: foo(1)
1
In [4]: foo(1,2,3)
1
2
3
The **kwargs
will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.
In [5]: def bar(**kwargs):
...: for a in kwargs:
...: print a, kwargs[a]
...:
...:
In [6]: bar(name='one', age=27)
age 27
name one
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs):
pass
Another usage of the *l
idiom is to unpack argument lists when calling a function.
In [9]: def foo(bar, lee):
...: print bar, lee
...:
...:
In [10]: l = [1,2]
In [11]: foo(*l)
1 2
In Python 3 it is possible to use *l
on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Also Python 3 adds new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
Such function accepts only 3 positional arguments, and everything after *
can only be passed as keyword arguments.
The *args
and **kwargs
is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
The *args
will give you all function parameters as a tuple:
In [1]: def foo(*args):
...: for a in args:
...: print a
...:
...:
In [2]: foo(1)
1
In [4]: foo(1,2,3)
1
2
3
The **kwargs
will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.
In [5]: def bar(**kwargs):
...: for a in kwargs:
...: print a, kwargs[a]
...:
...:
In [6]: bar(name='one', age=27)
age 27
name one
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs):
pass
Another usage of the *l
idiom is to unpack argument lists when calling a function.
In [9]: def foo(bar, lee):
...: print bar, lee
...:
...:
In [10]: l = [1,2]
In [11]: foo(*l)
1 2
In Python 3 it is possible to use *l
on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Also Python 3 adds new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
Such function accepts only 3 positional arguments, and everything after *
can only be passed as keyword arguments.
edited May 28 '17 at 12:54
gblomqvist
9018
9018
answered Aug 31 '08 at 15:17
Peter Hoffmann
34.1k116556
34.1k116556
5
The output of [6] is in reverse order. name one age 27
– thanos.a
Jan 8 '17 at 21:11
23
@thanos.a Python dicts, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. "The order of elements in**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - docs.python.org/3/whatsnew/3.6.html In fact, all dicts in CPython 3.6 will remember insertion order, but this is an implementation detail for now, and users should not rely on it.
– Aaron Hall♦
Jan 12 '17 at 20:47
"The**kwargs
will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary." Do I understand correctly that formal parameters are complementary to keyword arguments, together making all inputs to a function?
– Post169
May 15 '18 at 21:59
5
Very precise, clean, and easy to understand. I appreciate that you noted that it's an "unpacking operator", so that I could differentiate from passing by reference in C. +1
– bballdave025
Jun 8 '18 at 0:56
add a comment |
5
The output of [6] is in reverse order. name one age 27
– thanos.a
Jan 8 '17 at 21:11
23
@thanos.a Python dicts, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. "The order of elements in**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - docs.python.org/3/whatsnew/3.6.html In fact, all dicts in CPython 3.6 will remember insertion order, but this is an implementation detail for now, and users should not rely on it.
– Aaron Hall♦
Jan 12 '17 at 20:47
"The**kwargs
will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary." Do I understand correctly that formal parameters are complementary to keyword arguments, together making all inputs to a function?
– Post169
May 15 '18 at 21:59
5
Very precise, clean, and easy to understand. I appreciate that you noted that it's an "unpacking operator", so that I could differentiate from passing by reference in C. +1
– bballdave025
Jun 8 '18 at 0:56
5
5
The output of [6] is in reverse order. name one age 27
– thanos.a
Jan 8 '17 at 21:11
The output of [6] is in reverse order. name one age 27
– thanos.a
Jan 8 '17 at 21:11
23
23
@thanos.a Python dicts, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. "The order of elements in
**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - docs.python.org/3/whatsnew/3.6.html In fact, all dicts in CPython 3.6 will remember insertion order, but this is an implementation detail for now, and users should not rely on it.– Aaron Hall♦
Jan 12 '17 at 20:47
@thanos.a Python dicts, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. "The order of elements in
**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - docs.python.org/3/whatsnew/3.6.html In fact, all dicts in CPython 3.6 will remember insertion order, but this is an implementation detail for now, and users should not rely on it.– Aaron Hall♦
Jan 12 '17 at 20:47
"The
**kwargs
will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary." Do I understand correctly that formal parameters are complementary to keyword arguments, together making all inputs to a function?– Post169
May 15 '18 at 21:59
"The
**kwargs
will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary." Do I understand correctly that formal parameters are complementary to keyword arguments, together making all inputs to a function?– Post169
May 15 '18 at 21:59
5
5
Very precise, clean, and easy to understand. I appreciate that you noted that it's an "unpacking operator", so that I could differentiate from passing by reference in C. +1
– bballdave025
Jun 8 '18 at 0:56
Very precise, clean, and easy to understand. I appreciate that you noted that it's an "unpacking operator", so that I could differentiate from passing by reference in C. +1
– bballdave025
Jun 8 '18 at 0:56
add a comment |
It's also worth noting that you can use *
and **
when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
You can do things like:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
Note: The keys in mydict
have to be named exactly like the parameters of function foo
. Otherwise it will throw a TypeError
:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
add a comment |
It's also worth noting that you can use *
and **
when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
You can do things like:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
Note: The keys in mydict
have to be named exactly like the parameters of function foo
. Otherwise it will throw a TypeError
:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
add a comment |
It's also worth noting that you can use *
and **
when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
You can do things like:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
Note: The keys in mydict
have to be named exactly like the parameters of function foo
. Otherwise it will throw a TypeError
:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
It's also worth noting that you can use *
and **
when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
You can do things like:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
Note: The keys in mydict
have to be named exactly like the parameters of function foo
. Otherwise it will throw a TypeError
:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
edited Mar 7 '18 at 1:53
Trenton
6,31783751
6,31783751
answered Aug 31 '08 at 15:47
Lorin Hochstein
33.9k2285124
33.9k2285124
add a comment |
add a comment |
The single * means that there can be any number of extra positional arguments. foo()
can be invoked like foo(1,2,3,4,5)
. In the body of foo() param2 is a sequence containing 2-5.
The double ** means there can be any number of extra named parameters. bar()
can be invoked like bar(1, a=2, b=3)
. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }
With the following code:
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
foo(1,2,3,4,5)
bar(1,a=2,b=3)
the output is
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
add a comment |
The single * means that there can be any number of extra positional arguments. foo()
can be invoked like foo(1,2,3,4,5)
. In the body of foo() param2 is a sequence containing 2-5.
The double ** means there can be any number of extra named parameters. bar()
can be invoked like bar(1, a=2, b=3)
. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }
With the following code:
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
foo(1,2,3,4,5)
bar(1,a=2,b=3)
the output is
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
add a comment |
The single * means that there can be any number of extra positional arguments. foo()
can be invoked like foo(1,2,3,4,5)
. In the body of foo() param2 is a sequence containing 2-5.
The double ** means there can be any number of extra named parameters. bar()
can be invoked like bar(1, a=2, b=3)
. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }
With the following code:
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
foo(1,2,3,4,5)
bar(1,a=2,b=3)
the output is
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
The single * means that there can be any number of extra positional arguments. foo()
can be invoked like foo(1,2,3,4,5)
. In the body of foo() param2 is a sequence containing 2-5.
The double ** means there can be any number of extra named parameters. bar()
can be invoked like bar(1, a=2, b=3)
. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }
With the following code:
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
foo(1,2,3,4,5)
bar(1,a=2,b=3)
the output is
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
edited Dec 1 '18 at 5:59
Community♦
11
11
answered Aug 31 '08 at 15:20
nickd
2,96821524
2,96821524
add a comment |
add a comment |
What does
**
(double star) and*
(star) do for parameters
They allow for functions to be defined to accept and for users to pass any number of arguments, positional (*
) and keyword (**
).
Defining Functions
*args
allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args
.
**kwargs
allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs
.
You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, args
and kwargs
are standard names.
Expansion, Passing any number of arguments
You can also use *args
and **kwargs
to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.
The function recieving the parameters does not have to know that they are being expanded.
For example, Python 2's xrange does not explicitly expect *args
, but since it takes 3 integers as arguments:
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
As another example, we can use dict expansion in str.format
:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
New in Python 3: Defining functions with keyword only arguments
You can have keyword only arguments after the *args
- for example, here, kwarg2
must be given as a keyword argument - not positionally:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
Usage:
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
Also, *
can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
Here, kwarg2
again must be an explicitly named, keyword argument:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
And we can no longer accept unlimited positional arguments because we don't have *args*
:
>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were given
Again, more simply, here we require kwarg
to be given by name, not positionally:
def bar(*, kwarg=None):
return kwarg
In this example, we see that if we try to pass kwarg
positionally, we get an error:
>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
We must explicitly pass the kwarg
parameter as a keyword argument.
>>> bar(kwarg='kwarg')
'kwarg'
Python 2 compatible demos
*args
(typically said "star-args") and **kwargs
(stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the *
and **
notation. These specific variable names aren't required (e.g. you could use *foos
and **bars
), but a departure from convention is likely to enrage your fellow Python coders.
We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).
Example 1
The following function describes how they can be used, and demonstrates behavior. Note the named b
argument will be consumed by the second positional argument before :
def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
# - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
# - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: n{0}'.format(
dict(**kwargs), kweg=kweg))
We can check the online help for the function's signature, with help(foo)
, which tells us
foo(a, b=10, *args, **kwargs)
Let's call this function with foo(1, 2, 3, 4, e=5, f=6, g=7)
which prints:
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
Example 2
We can also call it using another function, into which we just provide a
:
def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
bar(100)
prints:
a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
Example 3: practical usage in decorators
OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.
def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()
def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()
def baz(a, b, c, d, e, f):
... and so on
We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how *args
and **kwargs
can be very useful:
def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:
@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)
@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)
@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)
@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
And by factoring out our code, which *args
and **kwargs
allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.
add a comment |
What does
**
(double star) and*
(star) do for parameters
They allow for functions to be defined to accept and for users to pass any number of arguments, positional (*
) and keyword (**
).
Defining Functions
*args
allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args
.
**kwargs
allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs
.
You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, args
and kwargs
are standard names.
Expansion, Passing any number of arguments
You can also use *args
and **kwargs
to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.
The function recieving the parameters does not have to know that they are being expanded.
For example, Python 2's xrange does not explicitly expect *args
, but since it takes 3 integers as arguments:
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
As another example, we can use dict expansion in str.format
:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
New in Python 3: Defining functions with keyword only arguments
You can have keyword only arguments after the *args
- for example, here, kwarg2
must be given as a keyword argument - not positionally:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
Usage:
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
Also, *
can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
Here, kwarg2
again must be an explicitly named, keyword argument:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
And we can no longer accept unlimited positional arguments because we don't have *args*
:
>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were given
Again, more simply, here we require kwarg
to be given by name, not positionally:
def bar(*, kwarg=None):
return kwarg
In this example, we see that if we try to pass kwarg
positionally, we get an error:
>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
We must explicitly pass the kwarg
parameter as a keyword argument.
>>> bar(kwarg='kwarg')
'kwarg'
Python 2 compatible demos
*args
(typically said "star-args") and **kwargs
(stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the *
and **
notation. These specific variable names aren't required (e.g. you could use *foos
and **bars
), but a departure from convention is likely to enrage your fellow Python coders.
We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).
Example 1
The following function describes how they can be used, and demonstrates behavior. Note the named b
argument will be consumed by the second positional argument before :
def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
# - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
# - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: n{0}'.format(
dict(**kwargs), kweg=kweg))
We can check the online help for the function's signature, with help(foo)
, which tells us
foo(a, b=10, *args, **kwargs)
Let's call this function with foo(1, 2, 3, 4, e=5, f=6, g=7)
which prints:
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
Example 2
We can also call it using another function, into which we just provide a
:
def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
bar(100)
prints:
a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
Example 3: practical usage in decorators
OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.
def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()
def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()
def baz(a, b, c, d, e, f):
... and so on
We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how *args
and **kwargs
can be very useful:
def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:
@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)
@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)
@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)
@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
And by factoring out our code, which *args
and **kwargs
allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.
add a comment |
What does
**
(double star) and*
(star) do for parameters
They allow for functions to be defined to accept and for users to pass any number of arguments, positional (*
) and keyword (**
).
Defining Functions
*args
allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args
.
**kwargs
allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs
.
You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, args
and kwargs
are standard names.
Expansion, Passing any number of arguments
You can also use *args
and **kwargs
to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.
The function recieving the parameters does not have to know that they are being expanded.
For example, Python 2's xrange does not explicitly expect *args
, but since it takes 3 integers as arguments:
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
As another example, we can use dict expansion in str.format
:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
New in Python 3: Defining functions with keyword only arguments
You can have keyword only arguments after the *args
- for example, here, kwarg2
must be given as a keyword argument - not positionally:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
Usage:
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
Also, *
can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
Here, kwarg2
again must be an explicitly named, keyword argument:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
And we can no longer accept unlimited positional arguments because we don't have *args*
:
>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were given
Again, more simply, here we require kwarg
to be given by name, not positionally:
def bar(*, kwarg=None):
return kwarg
In this example, we see that if we try to pass kwarg
positionally, we get an error:
>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
We must explicitly pass the kwarg
parameter as a keyword argument.
>>> bar(kwarg='kwarg')
'kwarg'
Python 2 compatible demos
*args
(typically said "star-args") and **kwargs
(stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the *
and **
notation. These specific variable names aren't required (e.g. you could use *foos
and **bars
), but a departure from convention is likely to enrage your fellow Python coders.
We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).
Example 1
The following function describes how they can be used, and demonstrates behavior. Note the named b
argument will be consumed by the second positional argument before :
def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
# - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
# - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: n{0}'.format(
dict(**kwargs), kweg=kweg))
We can check the online help for the function's signature, with help(foo)
, which tells us
foo(a, b=10, *args, **kwargs)
Let's call this function with foo(1, 2, 3, 4, e=5, f=6, g=7)
which prints:
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
Example 2
We can also call it using another function, into which we just provide a
:
def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
bar(100)
prints:
a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
Example 3: practical usage in decorators
OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.
def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()
def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()
def baz(a, b, c, d, e, f):
... and so on
We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how *args
and **kwargs
can be very useful:
def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:
@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)
@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)
@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)
@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
And by factoring out our code, which *args
and **kwargs
allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.
What does
**
(double star) and*
(star) do for parameters
They allow for functions to be defined to accept and for users to pass any number of arguments, positional (*
) and keyword (**
).
Defining Functions
*args
allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args
.
**kwargs
allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs
.
You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, args
and kwargs
are standard names.
Expansion, Passing any number of arguments
You can also use *args
and **kwargs
to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.
The function recieving the parameters does not have to know that they are being expanded.
For example, Python 2's xrange does not explicitly expect *args
, but since it takes 3 integers as arguments:
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
As another example, we can use dict expansion in str.format
:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
New in Python 3: Defining functions with keyword only arguments
You can have keyword only arguments after the *args
- for example, here, kwarg2
must be given as a keyword argument - not positionally:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
Usage:
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
Also, *
can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
Here, kwarg2
again must be an explicitly named, keyword argument:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
And we can no longer accept unlimited positional arguments because we don't have *args*
:
>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were given
Again, more simply, here we require kwarg
to be given by name, not positionally:
def bar(*, kwarg=None):
return kwarg
In this example, we see that if we try to pass kwarg
positionally, we get an error:
>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
We must explicitly pass the kwarg
parameter as a keyword argument.
>>> bar(kwarg='kwarg')
'kwarg'
Python 2 compatible demos
*args
(typically said "star-args") and **kwargs
(stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the *
and **
notation. These specific variable names aren't required (e.g. you could use *foos
and **bars
), but a departure from convention is likely to enrage your fellow Python coders.
We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).
Example 1
The following function describes how they can be used, and demonstrates behavior. Note the named b
argument will be consumed by the second positional argument before :
def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
# - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
# - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: n{0}'.format(
dict(**kwargs), kweg=kweg))
We can check the online help for the function's signature, with help(foo)
, which tells us
foo(a, b=10, *args, **kwargs)
Let's call this function with foo(1, 2, 3, 4, e=5, f=6, g=7)
which prints:
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
Example 2
We can also call it using another function, into which we just provide a
:
def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
bar(100)
prints:
a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
Example 3: practical usage in decorators
OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.
def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()
def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()
def baz(a, b, c, d, e, f):
... and so on
We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how *args
and **kwargs
can be very useful:
def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:
@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)
@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)
@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)
@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
And by factoring out our code, which *args
and **kwargs
allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.
edited Dec 20 '16 at 20:21
answered Oct 14 '14 at 16:34
Aaron Hall♦
169k49296248
169k49296248
add a comment |
add a comment |
Let us first understand what are positional arguments and keyword arguments.
Below is an example of function definition with Positional arguments.
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
So this is a function definition with positional arguments.
You can call it with keyword/named arguments as well:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
Now let us study an example of function definition with keyword arguments:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
You can call this function with positional arguments as well:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
So we now know function definitions with positional as well as keyword arguments.
Now let us study the '*' operator and '**' operator.
Please note these operators can be used in 2 areas:
a) function call
b) function definition
The use of '*' operator and '**' operator in function call.
Let us get straight to an example and then discuss it.
def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
print(a+b)
my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}
# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
# output is 3 in all three calls to sum function.
So remember
when the '*' or '**' operator is used in a function call -
'*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.
'**' operator unpacks a dictionary into arguments needed by function definition.
Now let us study the '*' operator use in function definition.
Example:
def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
sum = 0
for a in args:
sum+=a
print(sum)
sum(1,2,3,4) #positional args sent to function sum
#output:
10
In function definition the '*' operator packs the received arguments into a tuple.
Now let us see an example of '**' used in function definition:
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
sum=0
for k,v in args.items():
sum+=v
print(sum)
sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
In function definition The '**' operator packs the received arguments into a dictionary.
So remember:
In a function call the '*' unpacks data structure of tuple or list into positional or keyword arguments to be received by function definition.
In a function call the '**' unpacks data structure of dictionary into positional or keyword arguments to be received by function definition.
In a function definition the '*' packs positional arguments into a tuple.
In a function definition the '**' packs keyword arguments into a dictionary.
add a comment |
Let us first understand what are positional arguments and keyword arguments.
Below is an example of function definition with Positional arguments.
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
So this is a function definition with positional arguments.
You can call it with keyword/named arguments as well:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
Now let us study an example of function definition with keyword arguments:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
You can call this function with positional arguments as well:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
So we now know function definitions with positional as well as keyword arguments.
Now let us study the '*' operator and '**' operator.
Please note these operators can be used in 2 areas:
a) function call
b) function definition
The use of '*' operator and '**' operator in function call.
Let us get straight to an example and then discuss it.
def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
print(a+b)
my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}
# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
# output is 3 in all three calls to sum function.
So remember
when the '*' or '**' operator is used in a function call -
'*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.
'**' operator unpacks a dictionary into arguments needed by function definition.
Now let us study the '*' operator use in function definition.
Example:
def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
sum = 0
for a in args:
sum+=a
print(sum)
sum(1,2,3,4) #positional args sent to function sum
#output:
10
In function definition the '*' operator packs the received arguments into a tuple.
Now let us see an example of '**' used in function definition:
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
sum=0
for k,v in args.items():
sum+=v
print(sum)
sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
In function definition The '**' operator packs the received arguments into a dictionary.
So remember:
In a function call the '*' unpacks data structure of tuple or list into positional or keyword arguments to be received by function definition.
In a function call the '**' unpacks data structure of dictionary into positional or keyword arguments to be received by function definition.
In a function definition the '*' packs positional arguments into a tuple.
In a function definition the '**' packs keyword arguments into a dictionary.
add a comment |
Let us first understand what are positional arguments and keyword arguments.
Below is an example of function definition with Positional arguments.
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
So this is a function definition with positional arguments.
You can call it with keyword/named arguments as well:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
Now let us study an example of function definition with keyword arguments:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
You can call this function with positional arguments as well:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
So we now know function definitions with positional as well as keyword arguments.
Now let us study the '*' operator and '**' operator.
Please note these operators can be used in 2 areas:
a) function call
b) function definition
The use of '*' operator and '**' operator in function call.
Let us get straight to an example and then discuss it.
def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
print(a+b)
my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}
# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
# output is 3 in all three calls to sum function.
So remember
when the '*' or '**' operator is used in a function call -
'*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.
'**' operator unpacks a dictionary into arguments needed by function definition.
Now let us study the '*' operator use in function definition.
Example:
def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
sum = 0
for a in args:
sum+=a
print(sum)
sum(1,2,3,4) #positional args sent to function sum
#output:
10
In function definition the '*' operator packs the received arguments into a tuple.
Now let us see an example of '**' used in function definition:
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
sum=0
for k,v in args.items():
sum+=v
print(sum)
sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
In function definition The '**' operator packs the received arguments into a dictionary.
So remember:
In a function call the '*' unpacks data structure of tuple or list into positional or keyword arguments to be received by function definition.
In a function call the '**' unpacks data structure of dictionary into positional or keyword arguments to be received by function definition.
In a function definition the '*' packs positional arguments into a tuple.
In a function definition the '**' packs keyword arguments into a dictionary.
Let us first understand what are positional arguments and keyword arguments.
Below is an example of function definition with Positional arguments.
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
So this is a function definition with positional arguments.
You can call it with keyword/named arguments as well:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
Now let us study an example of function definition with keyword arguments:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
You can call this function with positional arguments as well:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
So we now know function definitions with positional as well as keyword arguments.
Now let us study the '*' operator and '**' operator.
Please note these operators can be used in 2 areas:
a) function call
b) function definition
The use of '*' operator and '**' operator in function call.
Let us get straight to an example and then discuss it.
def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
print(a+b)
my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}
# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
# output is 3 in all three calls to sum function.
So remember
when the '*' or '**' operator is used in a function call -
'*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.
'**' operator unpacks a dictionary into arguments needed by function definition.
Now let us study the '*' operator use in function definition.
Example:
def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
sum = 0
for a in args:
sum+=a
print(sum)
sum(1,2,3,4) #positional args sent to function sum
#output:
10
In function definition the '*' operator packs the received arguments into a tuple.
Now let us see an example of '**' used in function definition:
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
sum=0
for k,v in args.items():
sum+=v
print(sum)
sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
In function definition The '**' operator packs the received arguments into a dictionary.
So remember:
In a function call the '*' unpacks data structure of tuple or list into positional or keyword arguments to be received by function definition.
In a function call the '**' unpacks data structure of dictionary into positional or keyword arguments to be received by function definition.
In a function definition the '*' packs positional arguments into a tuple.
In a function definition the '**' packs keyword arguments into a dictionary.
edited Aug 6 '16 at 19:53
Brian Burns
6,40744445
6,40744445
answered Jan 20 '16 at 11:40
Karan Ahuja
59958
59958
add a comment |
add a comment |
*
and **
have special usage in the function argument list. *
implies that the argument is a list and **
implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments
add a comment |
*
and **
have special usage in the function argument list. *
implies that the argument is a list and **
implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments
add a comment |
*
and **
have special usage in the function argument list. *
implies that the argument is a list and **
implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments
*
and **
have special usage in the function argument list. *
implies that the argument is a list and **
implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments
edited Sep 11 '12 at 10:59
Bill the Lizard
290k157496786
290k157496786
answered Sep 11 '12 at 4:33
ronak
1,12211432
1,12211432
add a comment |
add a comment |
From the Python documentation:
If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax "*identifier" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).
If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax "**identifier" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.
add a comment |
From the Python documentation:
If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax "*identifier" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).
If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax "**identifier" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.
add a comment |
From the Python documentation:
If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax "*identifier" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).
If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax "**identifier" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.
From the Python documentation:
If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax "*identifier" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).
If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax "**identifier" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.
answered Aug 31 '08 at 15:07
Chris Upchurch
11.9k64564
11.9k64564
add a comment |
add a comment |
For those of you who learn by examples!
- The purpose of
*
is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g.f(*myList)
). - The purpose of
**
is to give you the ability to feed a function's arguments by providing a dictionary (e.g.f(**{'x' : 1, 'y' : 2})
).
Let us show this by defining a function that takes two normal variables x
, y
, and can accept more arguments as myArgs
, and can accept even more arguments as myKW
. Later, we will show how to feed y
using myArgDict
.
def f(x, y, *myArgs, **myKW):
print("# x = {}".format(x))
print("# y = {}".format(y))
print("# myArgs = {}".format(myArgs))
print("# myKW = {}".format(myKW))
print("# ----------------------------------------------------------------------")
# Define a list for demonstration purposes
myList = ["Left", "Right", "Up", "Down"]
# Define a dictionary for demonstration purposes
myDict = {"Wubba": "lubba", "Dub": "dub"}
# Define a dictionary to feed y
myArgDict = {'y': "Why?", 'y0': "Why not?", "q": "Here is a cue!"}
# The 1st elem of myList feeds y
f("myEx", *myList, **myDict)
# x = myEx
# y = Left
# myArgs = ('Right', 'Up', 'Down')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# y is matched and fed first
# The rest of myArgDict becomes additional arguments feeding myKW
f("myEx", **myArgDict)
# x = myEx
# y = Why?
# myArgs = ()
# myKW = {'y0': 'Why not?', 'q': 'Here is a cue!'}
# ----------------------------------------------------------------------
# The rest of myArgDict becomes additional arguments feeding myArgs
f("myEx", *myArgDict)
# x = myEx
# y = y
# myArgs = ('y0', 'q')
# myKW = {}
# ----------------------------------------------------------------------
# Feed extra arguments manually and append even more from my list
f("myEx", 4, 42, 420, *myList, *myDict, **myDict)
# x = myEx
# y = 4
# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# Without the stars, the entire provided list and dict become x, and y:
f(myList, myDict)
# x = ['Left', 'Right', 'Up', 'Down']
# y = {'Wubba': 'lubba', 'Dub': 'dub'}
# myArgs = ()
# myKW = {}
# ----------------------------------------------------------------------
Caveats
**
is exclusively reserved for dictionaries.- Non-optional argument assignment happens first.
- You cannot use a non-optional argument twice.
- If applicable,
**
must come after*
, always.
add a comment |
For those of you who learn by examples!
- The purpose of
*
is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g.f(*myList)
). - The purpose of
**
is to give you the ability to feed a function's arguments by providing a dictionary (e.g.f(**{'x' : 1, 'y' : 2})
).
Let us show this by defining a function that takes two normal variables x
, y
, and can accept more arguments as myArgs
, and can accept even more arguments as myKW
. Later, we will show how to feed y
using myArgDict
.
def f(x, y, *myArgs, **myKW):
print("# x = {}".format(x))
print("# y = {}".format(y))
print("# myArgs = {}".format(myArgs))
print("# myKW = {}".format(myKW))
print("# ----------------------------------------------------------------------")
# Define a list for demonstration purposes
myList = ["Left", "Right", "Up", "Down"]
# Define a dictionary for demonstration purposes
myDict = {"Wubba": "lubba", "Dub": "dub"}
# Define a dictionary to feed y
myArgDict = {'y': "Why?", 'y0': "Why not?", "q": "Here is a cue!"}
# The 1st elem of myList feeds y
f("myEx", *myList, **myDict)
# x = myEx
# y = Left
# myArgs = ('Right', 'Up', 'Down')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# y is matched and fed first
# The rest of myArgDict becomes additional arguments feeding myKW
f("myEx", **myArgDict)
# x = myEx
# y = Why?
# myArgs = ()
# myKW = {'y0': 'Why not?', 'q': 'Here is a cue!'}
# ----------------------------------------------------------------------
# The rest of myArgDict becomes additional arguments feeding myArgs
f("myEx", *myArgDict)
# x = myEx
# y = y
# myArgs = ('y0', 'q')
# myKW = {}
# ----------------------------------------------------------------------
# Feed extra arguments manually and append even more from my list
f("myEx", 4, 42, 420, *myList, *myDict, **myDict)
# x = myEx
# y = 4
# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# Without the stars, the entire provided list and dict become x, and y:
f(myList, myDict)
# x = ['Left', 'Right', 'Up', 'Down']
# y = {'Wubba': 'lubba', 'Dub': 'dub'}
# myArgs = ()
# myKW = {}
# ----------------------------------------------------------------------
Caveats
**
is exclusively reserved for dictionaries.- Non-optional argument assignment happens first.
- You cannot use a non-optional argument twice.
- If applicable,
**
must come after*
, always.
add a comment |
For those of you who learn by examples!
- The purpose of
*
is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g.f(*myList)
). - The purpose of
**
is to give you the ability to feed a function's arguments by providing a dictionary (e.g.f(**{'x' : 1, 'y' : 2})
).
Let us show this by defining a function that takes two normal variables x
, y
, and can accept more arguments as myArgs
, and can accept even more arguments as myKW
. Later, we will show how to feed y
using myArgDict
.
def f(x, y, *myArgs, **myKW):
print("# x = {}".format(x))
print("# y = {}".format(y))
print("# myArgs = {}".format(myArgs))
print("# myKW = {}".format(myKW))
print("# ----------------------------------------------------------------------")
# Define a list for demonstration purposes
myList = ["Left", "Right", "Up", "Down"]
# Define a dictionary for demonstration purposes
myDict = {"Wubba": "lubba", "Dub": "dub"}
# Define a dictionary to feed y
myArgDict = {'y': "Why?", 'y0': "Why not?", "q": "Here is a cue!"}
# The 1st elem of myList feeds y
f("myEx", *myList, **myDict)
# x = myEx
# y = Left
# myArgs = ('Right', 'Up', 'Down')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# y is matched and fed first
# The rest of myArgDict becomes additional arguments feeding myKW
f("myEx", **myArgDict)
# x = myEx
# y = Why?
# myArgs = ()
# myKW = {'y0': 'Why not?', 'q': 'Here is a cue!'}
# ----------------------------------------------------------------------
# The rest of myArgDict becomes additional arguments feeding myArgs
f("myEx", *myArgDict)
# x = myEx
# y = y
# myArgs = ('y0', 'q')
# myKW = {}
# ----------------------------------------------------------------------
# Feed extra arguments manually and append even more from my list
f("myEx", 4, 42, 420, *myList, *myDict, **myDict)
# x = myEx
# y = 4
# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# Without the stars, the entire provided list and dict become x, and y:
f(myList, myDict)
# x = ['Left', 'Right', 'Up', 'Down']
# y = {'Wubba': 'lubba', 'Dub': 'dub'}
# myArgs = ()
# myKW = {}
# ----------------------------------------------------------------------
Caveats
**
is exclusively reserved for dictionaries.- Non-optional argument assignment happens first.
- You cannot use a non-optional argument twice.
- If applicable,
**
must come after*
, always.
For those of you who learn by examples!
- The purpose of
*
is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g.f(*myList)
). - The purpose of
**
is to give you the ability to feed a function's arguments by providing a dictionary (e.g.f(**{'x' : 1, 'y' : 2})
).
Let us show this by defining a function that takes two normal variables x
, y
, and can accept more arguments as myArgs
, and can accept even more arguments as myKW
. Later, we will show how to feed y
using myArgDict
.
def f(x, y, *myArgs, **myKW):
print("# x = {}".format(x))
print("# y = {}".format(y))
print("# myArgs = {}".format(myArgs))
print("# myKW = {}".format(myKW))
print("# ----------------------------------------------------------------------")
# Define a list for demonstration purposes
myList = ["Left", "Right", "Up", "Down"]
# Define a dictionary for demonstration purposes
myDict = {"Wubba": "lubba", "Dub": "dub"}
# Define a dictionary to feed y
myArgDict = {'y': "Why?", 'y0': "Why not?", "q": "Here is a cue!"}
# The 1st elem of myList feeds y
f("myEx", *myList, **myDict)
# x = myEx
# y = Left
# myArgs = ('Right', 'Up', 'Down')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# y is matched and fed first
# The rest of myArgDict becomes additional arguments feeding myKW
f("myEx", **myArgDict)
# x = myEx
# y = Why?
# myArgs = ()
# myKW = {'y0': 'Why not?', 'q': 'Here is a cue!'}
# ----------------------------------------------------------------------
# The rest of myArgDict becomes additional arguments feeding myArgs
f("myEx", *myArgDict)
# x = myEx
# y = y
# myArgs = ('y0', 'q')
# myKW = {}
# ----------------------------------------------------------------------
# Feed extra arguments manually and append even more from my list
f("myEx", 4, 42, 420, *myList, *myDict, **myDict)
# x = myEx
# y = 4
# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# Without the stars, the entire provided list and dict become x, and y:
f(myList, myDict)
# x = ['Left', 'Right', 'Up', 'Down']
# y = {'Wubba': 'lubba', 'Dub': 'dub'}
# myArgs = ()
# myKW = {}
# ----------------------------------------------------------------------
Caveats
**
is exclusively reserved for dictionaries.- Non-optional argument assignment happens first.
- You cannot use a non-optional argument twice.
- If applicable,
**
must come after*
, always.
edited Aug 13 '18 at 19:43
answered May 22 '18 at 7:03
Miladiouss
502414
502414
add a comment |
add a comment |
While uses for the star/splat operators have been expanded in Python 3, I like the following table as it relates to use of these operators with functions. The splat operator(s) can be used both within function construction and in the function call:
In function *construction* In function *call*
=======================================================================
| def f(*args): | def f(a, b):
*args | for arg in args: | return a + b
| print(arg) | args = (1, 2)
| f(1, 2) | f(*args)
----------|--------------------------------|---------------------------
| def f(a, b): | def f(a, b):
**kwargs | return a + b | return a + b
| def g(**kwargs): | kwargs = dict(a=1, b=2)
| return f(**kwargs) | f(**kwargs)
| g(a=1, b=2) |
-----------------------------------------------------------------------
This really just serves to summarize Lorin Hochstein's answer but I find it helpful.
add a comment |
While uses for the star/splat operators have been expanded in Python 3, I like the following table as it relates to use of these operators with functions. The splat operator(s) can be used both within function construction and in the function call:
In function *construction* In function *call*
=======================================================================
| def f(*args): | def f(a, b):
*args | for arg in args: | return a + b
| print(arg) | args = (1, 2)
| f(1, 2) | f(*args)
----------|--------------------------------|---------------------------
| def f(a, b): | def f(a, b):
**kwargs | return a + b | return a + b
| def g(**kwargs): | kwargs = dict(a=1, b=2)
| return f(**kwargs) | f(**kwargs)
| g(a=1, b=2) |
-----------------------------------------------------------------------
This really just serves to summarize Lorin Hochstein's answer but I find it helpful.
add a comment |
While uses for the star/splat operators have been expanded in Python 3, I like the following table as it relates to use of these operators with functions. The splat operator(s) can be used both within function construction and in the function call:
In function *construction* In function *call*
=======================================================================
| def f(*args): | def f(a, b):
*args | for arg in args: | return a + b
| print(arg) | args = (1, 2)
| f(1, 2) | f(*args)
----------|--------------------------------|---------------------------
| def f(a, b): | def f(a, b):
**kwargs | return a + b | return a + b
| def g(**kwargs): | kwargs = dict(a=1, b=2)
| return f(**kwargs) | f(**kwargs)
| g(a=1, b=2) |
-----------------------------------------------------------------------
This really just serves to summarize Lorin Hochstein's answer but I find it helpful.
While uses for the star/splat operators have been expanded in Python 3, I like the following table as it relates to use of these operators with functions. The splat operator(s) can be used both within function construction and in the function call:
In function *construction* In function *call*
=======================================================================
| def f(*args): | def f(a, b):
*args | for arg in args: | return a + b
| print(arg) | args = (1, 2)
| f(1, 2) | f(*args)
----------|--------------------------------|---------------------------
| def f(a, b): | def f(a, b):
**kwargs | return a + b | return a + b
| def g(**kwargs): | kwargs = dict(a=1, b=2)
| return f(**kwargs) | f(**kwargs)
| g(a=1, b=2) |
-----------------------------------------------------------------------
This really just serves to summarize Lorin Hochstein's answer but I find it helpful.
edited Dec 2 '17 at 1:15
answered Nov 30 '17 at 18:28
Brad Solomon
13.1k73480
13.1k73480
add a comment |
add a comment |
I want to give an example which others haven't mentioned
* can also unpack a generator
An example from Python3 Document
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
unzip_x will be [1, 2, 3], unzip_y will be [4, 5, 6]
The zip() receives multiple iretable args, and return a generator.
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
add a comment |
I want to give an example which others haven't mentioned
* can also unpack a generator
An example from Python3 Document
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
unzip_x will be [1, 2, 3], unzip_y will be [4, 5, 6]
The zip() receives multiple iretable args, and return a generator.
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
add a comment |
I want to give an example which others haven't mentioned
* can also unpack a generator
An example from Python3 Document
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
unzip_x will be [1, 2, 3], unzip_y will be [4, 5, 6]
The zip() receives multiple iretable args, and return a generator.
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
I want to give an example which others haven't mentioned
* can also unpack a generator
An example from Python3 Document
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
unzip_x will be [1, 2, 3], unzip_y will be [4, 5, 6]
The zip() receives multiple iretable args, and return a generator.
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
answered Nov 8 '16 at 16:50
Lochu'an Chang
7113
7113
add a comment |
add a comment |
In Python 3.5, you can also use this syntax in list
, dict
, tuple
, and set
displays (also sometimes called literals). See PEP 488: Additional Unpacking Generalizations.
>>> (0, *range(1, 4), 5, *range(6, 8))
(0, 1, 2, 3, 5, 6, 7)
>>> [0, *range(1, 4), 5, *range(6, 8)]
[0, 1, 2, 3, 5, 6, 7]
>>> {0, *range(1, 4), 5, *range(6, 8)}
{0, 1, 2, 3, 5, 6, 7}
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> e = {'six': 6, 'seven': 7}
>>> {'zero': 0, **d, 'five': 5, **e}
{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
It also allows multiple iterables to be unpacked in a single function call.
>>> range(*[1, 10], *[2])
range(1, 10, 2)
(Thanks to mgilson for the PEP link.)
1
I'm not sure that this is a violation of "there's only one way to do it". There's no other way to initialize a list/tuple from multiple iterables -- You currently need to chain them into a single iterable which isn't always convenient. You can read about the rational in PEP-0448. Also, this isn't a python3.x feature, it's a python3.5+ feature :-).
– mgilson
Dec 8 '15 at 21:41
@mgilson, that would explain why it wasn't mentioned before.
– leewz
Dec 8 '15 at 22:23
add a comment |
In Python 3.5, you can also use this syntax in list
, dict
, tuple
, and set
displays (also sometimes called literals). See PEP 488: Additional Unpacking Generalizations.
>>> (0, *range(1, 4), 5, *range(6, 8))
(0, 1, 2, 3, 5, 6, 7)
>>> [0, *range(1, 4), 5, *range(6, 8)]
[0, 1, 2, 3, 5, 6, 7]
>>> {0, *range(1, 4), 5, *range(6, 8)}
{0, 1, 2, 3, 5, 6, 7}
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> e = {'six': 6, 'seven': 7}
>>> {'zero': 0, **d, 'five': 5, **e}
{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
It also allows multiple iterables to be unpacked in a single function call.
>>> range(*[1, 10], *[2])
range(1, 10, 2)
(Thanks to mgilson for the PEP link.)
1
I'm not sure that this is a violation of "there's only one way to do it". There's no other way to initialize a list/tuple from multiple iterables -- You currently need to chain them into a single iterable which isn't always convenient. You can read about the rational in PEP-0448. Also, this isn't a python3.x feature, it's a python3.5+ feature :-).
– mgilson
Dec 8 '15 at 21:41
@mgilson, that would explain why it wasn't mentioned before.
– leewz
Dec 8 '15 at 22:23
add a comment |
In Python 3.5, you can also use this syntax in list
, dict
, tuple
, and set
displays (also sometimes called literals). See PEP 488: Additional Unpacking Generalizations.
>>> (0, *range(1, 4), 5, *range(6, 8))
(0, 1, 2, 3, 5, 6, 7)
>>> [0, *range(1, 4), 5, *range(6, 8)]
[0, 1, 2, 3, 5, 6, 7]
>>> {0, *range(1, 4), 5, *range(6, 8)}
{0, 1, 2, 3, 5, 6, 7}
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> e = {'six': 6, 'seven': 7}
>>> {'zero': 0, **d, 'five': 5, **e}
{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
It also allows multiple iterables to be unpacked in a single function call.
>>> range(*[1, 10], *[2])
range(1, 10, 2)
(Thanks to mgilson for the PEP link.)
In Python 3.5, you can also use this syntax in list
, dict
, tuple
, and set
displays (also sometimes called literals). See PEP 488: Additional Unpacking Generalizations.
>>> (0, *range(1, 4), 5, *range(6, 8))
(0, 1, 2, 3, 5, 6, 7)
>>> [0, *range(1, 4), 5, *range(6, 8)]
[0, 1, 2, 3, 5, 6, 7]
>>> {0, *range(1, 4), 5, *range(6, 8)}
{0, 1, 2, 3, 5, 6, 7}
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> e = {'six': 6, 'seven': 7}
>>> {'zero': 0, **d, 'five': 5, **e}
{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
It also allows multiple iterables to be unpacked in a single function call.
>>> range(*[1, 10], *[2])
range(1, 10, 2)
(Thanks to mgilson for the PEP link.)
edited Dec 8 '15 at 22:29
answered Dec 8 '15 at 21:38
leewz
2,06411225
2,06411225
1
I'm not sure that this is a violation of "there's only one way to do it". There's no other way to initialize a list/tuple from multiple iterables -- You currently need to chain them into a single iterable which isn't always convenient. You can read about the rational in PEP-0448. Also, this isn't a python3.x feature, it's a python3.5+ feature :-).
– mgilson
Dec 8 '15 at 21:41
@mgilson, that would explain why it wasn't mentioned before.
– leewz
Dec 8 '15 at 22:23
add a comment |
1
I'm not sure that this is a violation of "there's only one way to do it". There's no other way to initialize a list/tuple from multiple iterables -- You currently need to chain them into a single iterable which isn't always convenient. You can read about the rational in PEP-0448. Also, this isn't a python3.x feature, it's a python3.5+ feature :-).
– mgilson
Dec 8 '15 at 21:41
@mgilson, that would explain why it wasn't mentioned before.
– leewz
Dec 8 '15 at 22:23
1
1
I'm not sure that this is a violation of "there's only one way to do it". There's no other way to initialize a list/tuple from multiple iterables -- You currently need to chain them into a single iterable which isn't always convenient. You can read about the rational in PEP-0448. Also, this isn't a python3.x feature, it's a python3.5+ feature :-).
– mgilson
Dec 8 '15 at 21:41
I'm not sure that this is a violation of "there's only one way to do it". There's no other way to initialize a list/tuple from multiple iterables -- You currently need to chain them into a single iterable which isn't always convenient. You can read about the rational in PEP-0448. Also, this isn't a python3.x feature, it's a python3.5+ feature :-).
– mgilson
Dec 8 '15 at 21:41
@mgilson, that would explain why it wasn't mentioned before.
– leewz
Dec 8 '15 at 22:23
@mgilson, that would explain why it wasn't mentioned before.
– leewz
Dec 8 '15 at 22:23
add a comment |
In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write __init__
method in Python. Similar usage can seen in frameworks like Django code.
For example,
def __init__(self, *args, **kwargs):
for attribute_name, value in zip(self._expected_attributes, args):
setattr(self, attribute_name, value)
if kwargs.has_key(attribute_name):
kwargs.pop(attribute_name)
for attribute_name in kwargs.viewkeys():
setattr(self, attribute_name, kwargs[attribute_name])
A subclass can then be
class RetailItem(Item):
_expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']
class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['expiry_date']
The subclass then be instantiated as
food_item = FoodItem(name = 'Jam',
price = 12.0,
category = 'Foods',
country_of_origin = 'US',
expiry_date = datetime.datetime.now())
Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class __init__
to offload the attributes setting.
This is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,
class ElectronicAccessories(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['specifications']
# Depend on args and kwargs to populate the data as needed.
def __init__(self, specifications = None, *args, **kwargs):
self.specifications = specifications # Rest of attributes will make sense to parent class.
super(ElectronicAccessories, self).__init__(*args, **kwargs)
which can be instatiated as
usb_key = ElectronicAccessories(name = 'Sandisk',
price = '$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
The complete code is here
1
1. Basically init is a method, so (in this context) it's not really different. 2. Use # for comments, not """, which just marks literal strings. 3. Using super should be the preferred way, especially for your example with multi-level inheritance.
– 0xc0de
Feb 21 '18 at 8:24
add a comment |
In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write __init__
method in Python. Similar usage can seen in frameworks like Django code.
For example,
def __init__(self, *args, **kwargs):
for attribute_name, value in zip(self._expected_attributes, args):
setattr(self, attribute_name, value)
if kwargs.has_key(attribute_name):
kwargs.pop(attribute_name)
for attribute_name in kwargs.viewkeys():
setattr(self, attribute_name, kwargs[attribute_name])
A subclass can then be
class RetailItem(Item):
_expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']
class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['expiry_date']
The subclass then be instantiated as
food_item = FoodItem(name = 'Jam',
price = 12.0,
category = 'Foods',
country_of_origin = 'US',
expiry_date = datetime.datetime.now())
Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class __init__
to offload the attributes setting.
This is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,
class ElectronicAccessories(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['specifications']
# Depend on args and kwargs to populate the data as needed.
def __init__(self, specifications = None, *args, **kwargs):
self.specifications = specifications # Rest of attributes will make sense to parent class.
super(ElectronicAccessories, self).__init__(*args, **kwargs)
which can be instatiated as
usb_key = ElectronicAccessories(name = 'Sandisk',
price = '$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
The complete code is here
1
1. Basically init is a method, so (in this context) it's not really different. 2. Use # for comments, not """, which just marks literal strings. 3. Using super should be the preferred way, especially for your example with multi-level inheritance.
– 0xc0de
Feb 21 '18 at 8:24
add a comment |
In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write __init__
method in Python. Similar usage can seen in frameworks like Django code.
For example,
def __init__(self, *args, **kwargs):
for attribute_name, value in zip(self._expected_attributes, args):
setattr(self, attribute_name, value)
if kwargs.has_key(attribute_name):
kwargs.pop(attribute_name)
for attribute_name in kwargs.viewkeys():
setattr(self, attribute_name, kwargs[attribute_name])
A subclass can then be
class RetailItem(Item):
_expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']
class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['expiry_date']
The subclass then be instantiated as
food_item = FoodItem(name = 'Jam',
price = 12.0,
category = 'Foods',
country_of_origin = 'US',
expiry_date = datetime.datetime.now())
Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class __init__
to offload the attributes setting.
This is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,
class ElectronicAccessories(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['specifications']
# Depend on args and kwargs to populate the data as needed.
def __init__(self, specifications = None, *args, **kwargs):
self.specifications = specifications # Rest of attributes will make sense to parent class.
super(ElectronicAccessories, self).__init__(*args, **kwargs)
which can be instatiated as
usb_key = ElectronicAccessories(name = 'Sandisk',
price = '$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
The complete code is here
In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write __init__
method in Python. Similar usage can seen in frameworks like Django code.
For example,
def __init__(self, *args, **kwargs):
for attribute_name, value in zip(self._expected_attributes, args):
setattr(self, attribute_name, value)
if kwargs.has_key(attribute_name):
kwargs.pop(attribute_name)
for attribute_name in kwargs.viewkeys():
setattr(self, attribute_name, kwargs[attribute_name])
A subclass can then be
class RetailItem(Item):
_expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']
class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['expiry_date']
The subclass then be instantiated as
food_item = FoodItem(name = 'Jam',
price = 12.0,
category = 'Foods',
country_of_origin = 'US',
expiry_date = datetime.datetime.now())
Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class __init__
to offload the attributes setting.
This is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,
class ElectronicAccessories(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['specifications']
# Depend on args and kwargs to populate the data as needed.
def __init__(self, specifications = None, *args, **kwargs):
self.specifications = specifications # Rest of attributes will make sense to parent class.
super(ElectronicAccessories, self).__init__(*args, **kwargs)
which can be instatiated as
usb_key = ElectronicAccessories(name = 'Sandisk',
price = '$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
The complete code is here
edited Feb 21 '18 at 9:02
user8595685
answered Aug 16 '15 at 4:23
HarisankarK
508214
508214
1
1. Basically init is a method, so (in this context) it's not really different. 2. Use # for comments, not """, which just marks literal strings. 3. Using super should be the preferred way, especially for your example with multi-level inheritance.
– 0xc0de
Feb 21 '18 at 8:24
add a comment |
1
1. Basically init is a method, so (in this context) it's not really different. 2. Use # for comments, not """, which just marks literal strings. 3. Using super should be the preferred way, especially for your example with multi-level inheritance.
– 0xc0de
Feb 21 '18 at 8:24
1
1
1. Basically init is a method, so (in this context) it's not really different. 2. Use # for comments, not """, which just marks literal strings. 3. Using super should be the preferred way, especially for your example with multi-level inheritance.
– 0xc0de
Feb 21 '18 at 8:24
1. Basically init is a method, so (in this context) it's not really different. 2. Use # for comments, not """, which just marks literal strings. 3. Using super should be the preferred way, especially for your example with multi-level inheritance.
– 0xc0de
Feb 21 '18 at 8:24
add a comment |
A good example of using both in a function is:
>>> def foo(*arg,**kwargs):
... print arg
... print kwargs
>>>
>>> a = (1, 2, 3)
>>> b = {'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(*a,**b)
(1, 2, 3)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,**b)
((1, 2, 3),)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,b)
((1, 2, 3), {'aa': 11, 'bb': 22})
{}
>>>
>>>
>>> foo(a,*b)
((1, 2, 3), 'aa', 'bb')
{}
add a comment |
A good example of using both in a function is:
>>> def foo(*arg,**kwargs):
... print arg
... print kwargs
>>>
>>> a = (1, 2, 3)
>>> b = {'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(*a,**b)
(1, 2, 3)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,**b)
((1, 2, 3),)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,b)
((1, 2, 3), {'aa': 11, 'bb': 22})
{}
>>>
>>>
>>> foo(a,*b)
((1, 2, 3), 'aa', 'bb')
{}
add a comment |
A good example of using both in a function is:
>>> def foo(*arg,**kwargs):
... print arg
... print kwargs
>>>
>>> a = (1, 2, 3)
>>> b = {'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(*a,**b)
(1, 2, 3)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,**b)
((1, 2, 3),)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,b)
((1, 2, 3), {'aa': 11, 'bb': 22})
{}
>>>
>>>
>>> foo(a,*b)
((1, 2, 3), 'aa', 'bb')
{}
A good example of using both in a function is:
>>> def foo(*arg,**kwargs):
... print arg
... print kwargs
>>>
>>> a = (1, 2, 3)
>>> b = {'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(*a,**b)
(1, 2, 3)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,**b)
((1, 2, 3),)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,b)
((1, 2, 3), {'aa': 11, 'bb': 22})
{}
>>>
>>>
>>> foo(a,*b)
((1, 2, 3), 'aa', 'bb')
{}
answered Oct 26 '16 at 12:48
amir jj
159113
159113
add a comment |
add a comment |
This example would help you remember *args
, **kwargs
and even super
and inheritance in Python at once.
class base(object):
def __init__(self, base_param):
self.base_param = base_param
class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1
add a comment |
This example would help you remember *args
, **kwargs
and even super
and inheritance in Python at once.
class base(object):
def __init__(self, base_param):
self.base_param = base_param
class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1
add a comment |
This example would help you remember *args
, **kwargs
and even super
and inheritance in Python at once.
class base(object):
def __init__(self, base_param):
self.base_param = base_param
class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1
This example would help you remember *args
, **kwargs
and even super
and inheritance in Python at once.
class base(object):
def __init__(self, base_param):
self.base_param = base_param
class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1
answered Nov 26 '16 at 21:09
thanhtang
378315
378315
add a comment |
add a comment |
*args
and **kwargs
: allow you to pass a variable number of arguments to a function.
*args
: is used to send a non-keyworded variable length argument list to the function:
def args(normal_arg, *argv):
print ("normal argument:",normal_arg)
for arg in argv:
print("Argument in list of arguments from *argv:", arg)
args('animals','fish','duck','bird')
Will produce:
normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird
**kwargs*
**kwargs
allows you to pass keyworded variable length of arguments to a function. You should use **kwargs
if you want to handle named arguments in a function.
def who(**kwargs):
if kwargs is not None:
for key, value in kwargs.items():
print ("Your %s is %s." %(key,value))
who (name="Nikola", last_name="Tesla", birthday = "7.10.1856", birthplace = "Croatia")
Will produce:
Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.
add a comment |
*args
and **kwargs
: allow you to pass a variable number of arguments to a function.
*args
: is used to send a non-keyworded variable length argument list to the function:
def args(normal_arg, *argv):
print ("normal argument:",normal_arg)
for arg in argv:
print("Argument in list of arguments from *argv:", arg)
args('animals','fish','duck','bird')
Will produce:
normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird
**kwargs*
**kwargs
allows you to pass keyworded variable length of arguments to a function. You should use **kwargs
if you want to handle named arguments in a function.
def who(**kwargs):
if kwargs is not None:
for key, value in kwargs.items():
print ("Your %s is %s." %(key,value))
who (name="Nikola", last_name="Tesla", birthday = "7.10.1856", birthplace = "Croatia")
Will produce:
Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.
add a comment |
*args
and **kwargs
: allow you to pass a variable number of arguments to a function.
*args
: is used to send a non-keyworded variable length argument list to the function:
def args(normal_arg, *argv):
print ("normal argument:",normal_arg)
for arg in argv:
print("Argument in list of arguments from *argv:", arg)
args('animals','fish','duck','bird')
Will produce:
normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird
**kwargs*
**kwargs
allows you to pass keyworded variable length of arguments to a function. You should use **kwargs
if you want to handle named arguments in a function.
def who(**kwargs):
if kwargs is not None:
for key, value in kwargs.items():
print ("Your %s is %s." %(key,value))
who (name="Nikola", last_name="Tesla", birthday = "7.10.1856", birthplace = "Croatia")
Will produce:
Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.
*args
and **kwargs
: allow you to pass a variable number of arguments to a function.
*args
: is used to send a non-keyworded variable length argument list to the function:
def args(normal_arg, *argv):
print ("normal argument:",normal_arg)
for arg in argv:
print("Argument in list of arguments from *argv:", arg)
args('animals','fish','duck','bird')
Will produce:
normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird
**kwargs*
**kwargs
allows you to pass keyworded variable length of arguments to a function. You should use **kwargs
if you want to handle named arguments in a function.
def who(**kwargs):
if kwargs is not None:
for key, value in kwargs.items():
print ("Your %s is %s." %(key,value))
who (name="Nikola", last_name="Tesla", birthday = "7.10.1856", birthplace = "Croatia")
Will produce:
Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.
edited May 1 '18 at 13:29
Ryan Schaefer
1,09711026
1,09711026
answered May 1 '18 at 12:54
Harvey
378411
378411
add a comment |
add a comment |
*
means receive variable arguments as list
**
means receive variable arguments as dictionary
Used like the following:
1) single *
def foo(*args):
for arg in args:
print(arg)
foo("two", 3)
Output:
two
3
2) Now **
def bar(**kwargs):
for key in kwargs:
print(key, kwargs[key])
bar(dic1="two", dic2=3)
Output:
dic1 two
dic2 3
add a comment |
*
means receive variable arguments as list
**
means receive variable arguments as dictionary
Used like the following:
1) single *
def foo(*args):
for arg in args:
print(arg)
foo("two", 3)
Output:
two
3
2) Now **
def bar(**kwargs):
for key in kwargs:
print(key, kwargs[key])
bar(dic1="two", dic2=3)
Output:
dic1 two
dic2 3
add a comment |
*
means receive variable arguments as list
**
means receive variable arguments as dictionary
Used like the following:
1) single *
def foo(*args):
for arg in args:
print(arg)
foo("two", 3)
Output:
two
3
2) Now **
def bar(**kwargs):
for key in kwargs:
print(key, kwargs[key])
bar(dic1="two", dic2=3)
Output:
dic1 two
dic2 3
*
means receive variable arguments as list
**
means receive variable arguments as dictionary
Used like the following:
1) single *
def foo(*args):
for arg in args:
print(arg)
foo("two", 3)
Output:
two
3
2) Now **
def bar(**kwargs):
for key in kwargs:
print(key, kwargs[key])
bar(dic1="two", dic2=3)
Output:
dic1 two
dic2 3
edited Aug 7 '18 at 18:36
answered Aug 7 '18 at 18:28
ishandutta2007
4,41454157
4,41454157
add a comment |
add a comment |
def foo(param1, *param2):
is a method can accept arbitrary number of values for*param2
,
def bar(param1, **param2):
is a method can accept arbitrary number of values with keys for*param2
param1
is a simple parameter.
For example, the syntax for implementing varargs in Java as follows:
accessModifier methodName(datatype… arg) {
// method body
}
add a comment |
def foo(param1, *param2):
is a method can accept arbitrary number of values for*param2
,
def bar(param1, **param2):
is a method can accept arbitrary number of values with keys for*param2
param1
is a simple parameter.
For example, the syntax for implementing varargs in Java as follows:
accessModifier methodName(datatype… arg) {
// method body
}
add a comment |
def foo(param1, *param2):
is a method can accept arbitrary number of values for*param2
,
def bar(param1, **param2):
is a method can accept arbitrary number of values with keys for*param2
param1
is a simple parameter.
For example, the syntax for implementing varargs in Java as follows:
accessModifier methodName(datatype… arg) {
// method body
}
def foo(param1, *param2):
is a method can accept arbitrary number of values for*param2
,
def bar(param1, **param2):
is a method can accept arbitrary number of values with keys for*param2
param1
is a simple parameter.
For example, the syntax for implementing varargs in Java as follows:
accessModifier methodName(datatype… arg) {
// method body
}
answered Sep 2 '18 at 5:14
Premraj
29k10152116
29k10152116
add a comment |
add a comment |
*args = *aList = all elements in a List
**args= ** aDict =all items in a dict
add a comment |
*args = *aList = all elements in a List
**args= ** aDict =all items in a dict
add a comment |
*args = *aList = all elements in a List
**args= ** aDict =all items in a dict
*args = *aList = all elements in a List
**args= ** aDict =all items in a dict
edited Dec 8 '17 at 1:43
answered Dec 8 '17 at 1:36
JawSaw
4,16311634
4,16311634
add a comment |
add a comment |
protected by Moinuddin Quadri Jan 22 '17 at 14:33
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
see also stackoverflow.com/questions/6967632/…
– Aaron Hall♦
Mar 1 '18 at 20:53
Related: Why use packed *args/**kwargs instead of passing list/dict?
– Steven M. Vascellaro
Mar 7 '18 at 21:26
More great insight: stackoverflow.com/a/11315061/4561887
– Gabriel Staples
Nov 16 '18 at 20:47
See also stackoverflow.com/questions/14301967/… for a bare asterisk
– naught101
Dec 13 '18 at 3:43