dataclasses.KW_ONLY Forces Keyword Arguments

Mark trailing dataclass fields with KW_ONLY so callers must pass them by name, inspect keyword-only fields, and catch the positional TypeError.

PythonConfig Management

Code

pythonsnippet
29 lines
from dataclasses import KW_ONLY, dataclass, fields


@dataclass
class Request:
    url: str
    method: str = "GET"
    _: KW_ONLY
    timeout: float = 5.0
    retries: int = 2


def main() -> None:
    request = Request("https://api.example.com", timeout=1.5)
    print(request)
    print("timeout:", request.timeout)
    print("retries:", request.retries)

    try:
        Request("https://api.example.com", "GET", 1.5)
    except TypeError as error:
        print("positional rejected:", error)

    keyword_only = [field.name for field in fields(Request) if field.kw_only]
    print("keyword-only fields:", keyword_only)


if __name__ == "__main__":
    main()

What the code does

dataclasses.KW_ONLY Forces Keyword Arguments is built around the class class and the function main.

Points of care

  • Entirely standard-library — copy it in and it runs.

Applying it

Signature: def main() -> None

Look for the timeout:, retries:, positional rejected: prefixes when the file runs; they tie each line to its step.

Statements that matter

except TypeError as error:
    print("positional rejected:", error)

Interactive Tools for This Topic

FAQ

What does dataclasses.KW_ONLY Forces Keyword Arguments print when run?
Execute the whole file; each printed line is prefixed with a label like `timeout:`, `retries:`, `positional rejected:`.