Keyword Arguments
In Python, function arguments can be passed by keyword.
- Example:
def remainder(number, divisor): return number % divisor # We can call `remainder` method in several ways remainder(20, 7) remainder(20, divisor=7) remainder(number=20, divisor=7) remainder(divisor=7, number=20)
- The order of keyword arguments does not matter
- Positional arguments must come before keyword arguments:
# This will raise an error remainder(number=20, 7)
**
Operator
We can use a dictionary when passing keyword arguments.
- Example:
kwarg_dict = { 'number': 20, 'divisor': 7 } # We can pass keyword arguments this way: remainder(**kwarg_dict) # The above is equivalent to `remainder(number=20, divisor=7)` divisor_dict = { 'divisor': 7 } # We can also mix ** operator with positional or keyword arguments: remainder(number=20, **divisor_dict)
Benefits of Keyword Arguments
Keyword arguments make function more readable When we specify keywords such s
remainder(number=20, divisor=7)
, it becomes clearer to see what the arguments are.Keyword arguments can have default values in the function definition This helps reduce repetitive code. We can still override the value when needed. When default value is assigned, the keyword argument is optional.
Keyword arguments provide a way to extend a function’s paramters while remaining backward compatible with existing callers
# If we had a method initially
def flow_rate(weight_diff, time_diff):
return weight_diff / time_diff
# We can extend this function while still allowing initial function calls
def flow_rate(weight_diff, time_diff, period=1, units_per_kg=1):
return ((weight_diff * units_per_kg) / time_diff_) * period
# If there was `flow_rate(weight_diff=2, time_diff=1)`, this would still work here.
Advice on Using Keyword Arguments
“The best practice is to always specify optional arguments using the keyword names and never pass them as positional arguments.”
Reference
- Effective Python: Item 23: Provide Optional Behavior with Keyword Arguments