Functions

Keyword-only Arguments

Use * to require selected function arguments to be named.

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=5
A bare * divides positional or keyword arguments from keyword-only ones; callers must pass c and d by name.

Naming 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=10

Flags are especially good keyword-only arguments because a bare positional False is hard to interpret.

Source

connect("localhost", secure=False)

Output

http://localhost timeout=5

The bare * is enforced at the call site: passing the timeout positionally raises TypeError instead of silently filling the wrong slot.

Source

try:
    connect("example.com", 10)
except TypeError as error:
    print(type(error).__name__)

Output

TypeError

Notes

See also

Run the complete example

Example code

Expected output

https://example.com timeout=5
https://example.com timeout=10
http://localhost timeout=5
TypeError

Execution time appears here after you run the example.