Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attributes without a default cannot follow attributes with one #17731

Open
embecka opened this issue Sep 3, 2024 · 1 comment · May be fixed by #17785
Open

Attributes without a default cannot follow attributes with one #17731

embecka opened this issue Sep 3, 2024 · 1 comment · May be fixed by #17785
Labels
bug mypy got something wrong

Comments

@embecka
Copy link

embecka commented Sep 3, 2024

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
@embecka embecka added the bug mypy got something wrong label Sep 3, 2024
@embecka
Copy link
Author

embecka commented Sep 19, 2024

I think

found_default = found_default or (attr.has_default and attr.is_in_init)
should be

found_default = found_default or (attr.has_default and attr.is_in_init and not attr.kw_only)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant