Functions
Keyword-only Arguments
Parameters after * must be named. The default options still apply when the caller omits them.
Source
def connect(host, *, timeout=5, secure=True):
scheme = "https" if secure else "http"
print(f"{scheme}://{host} timeout={timeout}")
connect("example.com")Output
https://example.com timeout=5Naming the option makes the call site explicit. A reader does not have to remember which positional slot controls the timeout.
Source
connect("example.com", timeout=10)Output
https://example.com timeout=10Flags are especially good keyword-only arguments because a bare positional False is hard to interpret.
Source
connect("localhost", secure=False)Output
http://localhost timeout=5Notes
- Put
*before options that callers should name. - Keyword-only flags avoid mysterious positional
TrueandFalsearguments. - Defaults work normally for keyword-only parameters.
See also
- related: Functions
- related: Args and Kwargs
- related: Positional-only Parameters
- related: Partial Functions
Run the complete example
Expected output
https://example.com timeout=5
https://example.com timeout=10
http://localhost timeout=5
Execution time appears here after you run the example.