Keyword-only arguments are arguments that can only be supplied to a function by keyword. In Python they are defined by a single asterisk in a function's signature. For example:
>>> def foo(bar, *, baz): print(bar, baz) >>> foo(1, baz=2) 1 2 >>> foo(1, 2) TypeError: foo() takes 1 positional argument but 2 were given
Using them has not only stylistic advantages and disadvantages but functional as well. Here are some that I'm aware of:
- It's less error-prone. When having positional arguments in a function call, changing a signature can break things. With keyword-only arguments there is no such a problem. (https://bugs.python.org/issue26729, https://bugs.python.org/issue18726, https://bugs.python.org/issue25628)
Making all arguments keyword-only won't allow to use the function with
map. For example:
>>> def square(*, x): return x * 2 >>> list(map(square, [1, 2, 3])) TypeError: square() takes 0 positional arguments but 1 was given
I couldn't find a general description on how I should properly use the keyword-only arguments in PEP 3102 that proposed them in the first place or in any other sources.
So, my questions are: Are there any other pitfalls that I'm unaware of when using keyword-only arguments? How can I safely use them without potentially break something in the future?