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

Add runtime __slots__ attribute to dataclasses #15649

Merged
merged 1 commit into from Jul 12, 2023
Merged

Conversation

sobolevn
Copy link
Member

Closes #15647

info.slots = generated_slots

# Now, insert `.__slots__` attribute to class namespace:
slots_type = TupleType(
[self._api.named_type("builtins.str") for _ in generated_slots],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worth creating Literal types here? So the inferred type in the test cases would be tuple[Literal["x"], Literal["y"], Literal["z"]].

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, because regular classes produce the same result:

class A:
    __slots__ = ('a', 'b')

reveal_type(A.__slots__)  # N: Revealed type is "tuple[builtins.str, builtins.str]"

__match_args__ attribute needs Literal to handle match kwargs correctly, but __slots__ does not need it at all.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I feel like we might get an issue at some point asking that we use the literal types, but it's fine if we're consistent with how explicit __slots__ works.

@github-actions
Copy link
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@JelleZijlstra JelleZijlstra merged commit 4a1a38e into master Jul 12, 2023
18 checks passed
@JelleZijlstra JelleZijlstra deleted the issue-15647 branch July 12, 2023 19:51
sobolevn added a commit that referenced this pull request Jul 12, 2023
This is similar to #15649 but for
`attrs` :)
Refs #15647
gertvdijk added a commit to gertvdijk/purepythonmilter that referenced this pull request Aug 10, 2023
Observed before this change with mypy==1.5.0:

    error: Trying to assign name "[...]" that is not in "__slots__" of type
    "purepythonmilter.server.session.MtaMilterSession"  [misc]

Mypy gained this feature to learn __slots__ for dataclasses (here via
attrs classes) in python/mypy#15649.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

mypy complaining that class annotated with @dataclass(slots=True) has no attribute __slots__
2 participants