Positional and Keyword Arguments (Livehacking Screenplay)¶
Plain Function with Positional Arguments¶
def f(a, b):
print(a, b)
f(1, 2)
f(a=3, b=4)
$ python code/10-plain-positional.py
1 2
3 4
Arbitrary Number of Arguments?¶
def f(*args):
print(args)
f(1, 2, 3)
$ python code/20-arbitrary-positional-tuple.py
(1, 2, 3)
|
|
def f(*args):
print(*args)
f(1, 2, 3)
$ python code/30-unpack-positional.py
1 2 3
Unpack any sequence as positional arguments?
l = [1,2,3]
print(*l)
$ python code/40-unpack-any-sequence-positional.py
1 2 3
And Keyword Arguments?¶
*args
⟶ no parameter namesno keyword arguments
def f(**kwargs):
print(kwargs)
f(a=1, b=2)
$ python code/50-keyword-dict.py
{'a': 1, 'b': 2}
A-ha: similar to
*args
,**kwargs
is passed as dictionaryAnd unpacking ⟶ same:
**