- 5.1 Function Definitions
- 5.2 Default Arguments
- 5.3 Variadic Arguments
- 5.4 Keyword Arguments
- 5.5 Variadic Keyword Arguments
- 5.6 Functions Accepting All Inputs
- 5.7 Positional-Only Arguments
- 5.8 Names, Documentation Strings, and Type Hints
- 5.9 Function Application and Parameter Passing
- 5.10 Return Values
- 5.11 Error Handling
- 5.12 Scoping Rules
- 5.13 Recursion
- 5.14 The lambda Expression
- 5.15 Higher-Order Functions
- 5.16 Argument Passing in Callback Functions
- 5.17 Returning Results from Callbacks
- 5.18 Decorators
- 5.19 Map, Filter, and Reduce
- 5.20 Function Introspection, Attributes, and Signatures
- 5.21 Environment Inspection
- 5.22 Dynamic Code Execution and Creation
- 5.23 Asynchronous Functions and await
- 5.24 Final Words: Thoughts on Functions and Composition
5.4 Keyword Arguments
Function arguments can be supplied by explicitly naming each parameter and specifying a value. These are known as keyword arguments. Here is an example:
def func(w, x, y, z): statements # Keyword argument invocation func(x=3, y=22, w='hello', z=[1, 2])
With keyword arguments, the order of the arguments doesn’t matter as long as each required parameter gets a single value. If you omit any of the required arguments or if the name of a keyword doesn’t match any of the parameter names in the function definition, a TypeError exception is raised. Keyword arguments are evaluated in the same order as they are specified in the function call.
Positional arguments and keyword arguments can appear in the same function call, provided that all the positional arguments appear first, values are provided for all nonoptional arguments, and no argument receives more than one value. Here’s an example:
func('hello', 3, z=[1, 2], y=22) func(3, 22, w='hello', z=[1, 2]) # TypeError. Multiple values for w
If desired, it is possible to force the use of keyword arguments. This is done by listing parameters after a * argument or just by including a single * in the definition. For example:
def read_data(filename, *, debug=False): ... def product(first, *values, scale=1): result = first * scale for val in values: result = result * val return result
In this example, the debug argument to read_data() can only be specified by keyword. This restriction often improves code readability:
data = read_data('Data.csv', True) # NO. TypeError data = read_data('Data.csv', debug=True) # Yes.
The product() function takes any number of positional arguments and an optional keyword-only argument. For example:
result = product(2,3,4) # Result = 24 result = product(2,3,4, scale=10) # Result = 240