Python › Dataclasses & NamedTuples

How would you use Python 3.10+'s kw_only=True (or per-field kw_only) to require dataclass fields be passed as keyword arguments only?

Advanced

Answer

Setting kw_only=True on @dataclass (or on an individual field()) forces those fields to be passed by KEYWORD ONLY in __init__, completely sidestepping the 'non-default argument follows default argument' ordering restriction, since keyword-only arguments don't have the same strict positional ordering requirement.
@dataclass(kw_only=True)
class Config:
    debug: bool = False
    name: str  # no default, but still valid since ALL fields are keyword-only now

c = Config(name="MyApp")  # must use keyword args: Config(name="MyApp", debug=True)
# Config("MyApp")  # TypeError: takes 1 positional argument but 2 were given
Real-world example Designing a configuration dataclass with many optional fields where enforcing keyword-only construction improves call-site readability.

Common follow-ups: Can you mix kw_only fields with regular positional fields in the SAME dataclass, and if so, how are they ordered?