Sub topic 3
Positional-Only Parameters and Flexible Calls
Assume you can define and call Python functions, use lists and dictionaries, and read simple TypeError messages. This chapter covers function signatures that control how callers provide arguments.
Positional-only parameters with `/`
A slash marks parameters that must be passed by position. Callers cannot use their parameter names:
def clamp(value, /, low=0, high=100):
return max(low, min(value, high))
print(clamp(150)) # 100
print(clamp(-5, high=10)) # 0
# clamp(value=5) # TypeErrorUsing / can protect an API from callers depending on a parameter name that you may want to change later.
Collecting and unpacking arguments
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.
def describe(*args, **kwargs):
return args, kwargs
print(describe(1, 2, color="blue"))
# ((1, 2), {"color": "blue"})In a call, * unpacks a sequence into positional arguments. ** unpacks a dictionary into keyword arguments.
def connect(host, port=5432, *, timeout=10):
return host, port, timeout
values = ["db.local", 6000]
options = {"timeout": 5}
print(connect(*values, **options))
# ('db.local', 6000, 5)Common binding errors
Python raises TypeError when arguments cannot bind to parameters. Common causes include:
- Supplying a positional-only parameter by keyword.
- Giving one parameter both a positional and keyword value.
- Omitting a required parameter.
- Passing an unexpected keyword.
- Supplying too many positional arguments.
Read the message for the parameter name and the kind of binding that failed.
Inspecting signatures and choosing an interface
The inspect module shows a function's signature. Defaults are also stored in __defaults__ and __kwdefaults__.
import inspect
def fetch(path, retries=3, *, timeout=10):
pass
print(inspect.signature(fetch))
print(fetch.__defaults__)
print(fetch.__kwdefaults__)Use positional parameters for short, obvious values. Use keyword-only parameters for options where names improve clarity. Use positional-only parameters when parameter names are an implementation detail. Prefer explicit parameters over unrestricted *args and **kwargs when the accepted inputs are known.
Exercise
Why does connect("db.local", timeout=5) work when connect("db.local", 5) does not for the function shown above?
Show answer
timeout appears after *, so it is keyword-only and must be passed with its name.