*args and **kwargs

Matt Ruffalo matt.ruffalo at gmail.com
Sun Sep 4 16:04:30 EDT 2016


On 2016-09-02 15:44, Ben Finney wrote:
> Note that this has nothing to do with how the function is defined; in
> the definition of the function, parameters are neither positional nor
> keyword. You name each of them, and you define an order for them; and
> neither of those makes any of them “positional” or “keyword”.
> Rather, “positional argument and “keyword argument” are characteristics of the arguments you *supply* in a particular call to the function.
>

To be fair, this isn't quite the case. One can define keyword-only
arguments, which must be supplied as such and don't really have an "order":

"""
>>> def f(arg1, arg2, *, arg3=None):
...     pass
...
>>> f(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 2 positional arguments but 3 were given
"""

One can even omit the default argument for something keyword-only, which
results in the consistent-but-initially-surprising situation of having a
required keyword argument:

"""
>>> def g(arg1, arg2, *, arg3):
...     pass
...
>>> g(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: g() takes 2 positional arguments but 3 were given
"""

MMR...



More information about the Python-list mailing list