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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.