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

[1.1 backport] [dataclass_transform] include __dataclass_fields__ in transformed types (#14752) #14769

Merged
merged 1 commit into from
Feb 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,17 +648,18 @@ def _is_kw_only_type(self, node: Type | None) -> bool:
return node_type.type.fullname == "dataclasses.KW_ONLY"

def _add_dataclass_fields_magic_attribute(self) -> None:
# Only add if the class is a dataclasses dataclass, and omit it for dataclass_transform
# classes.
# It would be nice if this condition were reified rather than using an `is` check.
# Only add if the class is a dataclasses dataclass, and omit it for dataclass_transform
# classes.
if self._spec is not _TRANSFORM_SPEC_FOR_DATACLASSES:
return

attr_name = "__dataclass_fields__"
any_type = AnyType(TypeOfAny.explicit)
field_type = self._api.named_type_or_none("dataclasses.Field", [any_type]) or any_type
# For `dataclasses`, use the type `dict[str, Field[Any]]` for accuracy. For dataclass
# transforms, it's inaccurate to use `Field` since a given transform may use a completely
# different type (or none); fall back to `Any` there.
#
# In either case, we're aiming to match the Typeshed stub for `is_dataclass`, which expects
# the instance to have a `__dataclass_fields__` attribute of type `dict[str, Field[Any]]`.
if self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:
field_type = self._api.named_type_or_none("dataclasses.Field", [any_type]) or any_type
else:
field_type = any_type
attr_type = self._api.named_type(
"builtins.dict", [self._api.named_type("builtins.str"), field_type]
)
Expand Down
3 changes: 1 addition & 2 deletions test-data/unit/check-dataclass-transform.test
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,7 @@ class Bad:
bad1: int = field(alias=some_str()) # E: "alias" argument to dataclass field must be a string literal
bad2: int = field(kw_only=some_bool()) # E: "kw_only" argument must be a boolean literal

# this metadata should only exist for dataclasses.dataclass classes
Foo.__dataclass_fields__ # E: "Type[Foo]" has no attribute "__dataclass_fields__"
reveal_type(Foo.__dataclass_fields__) # N: Revealed type is "builtins.dict[builtins.str, Any]"

[typing fixtures/typing-full.pyi]
[builtins fixtures/dataclasses.pyi]
Expand Down