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
def f(a, b, *, c, d): …positional or kwkeyword only
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

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

Execution time appears here after you run the example.