Skip to content

Attributes without a default cannot follow attributes with one #17731

@embecka

Description

@embecka

Bug Report

In dataclasses, attributes without a default cannot follow attributes with one unless they are keyword-only arguments. By setting the parameter kw_only=True of the dataclass decorator, all fields of the class are marked as keyword-only. By setting the parameter kw_only=True of the field function, the annotated attribute is marked as keyword-only. The problem occurs when an argument with a default is marked as keyword-only by using the field function but not the dataclass decorator, and is followed by another argument without a default. mypy reports an error, but it shouldn't.

To Reproduce

# example.py
from dataclasses import dataclass, field


@dataclass
class User:
    id: int = field(kw_only=True, default=0)
    name: str

Playground

Actual Behavior

mypy finds the following issue:

example.py:8: error: Attributes without a default cannot follow attributes with one  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.11.2
  • Mypy command-line flags: strict
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions