Skip to content

[ty] Implement DataClassInstance protocol for dataclasses. #18018

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

Merged
merged 6 commits into from
May 13, 2025
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: 19 additions & 0 deletions crates/ty_python_semantic/resources/mdtest/dataclasses.md
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,25 @@ reveal_type(C.__init__) # revealed: (field: str | int = int) -> None

To do

## `dataclass.fields`

Dataclasses have `__dataclass_fields__` in them, which makes them a subtype of the
`DataclassInstance` protocol.

Here, we verify that dataclasses can be passed to `dataclasses.fields` without any errors, and that
the return type of `dataclasses.fields` is correct.

```py
from dataclasses import dataclass, fields

@dataclass
class Foo:
x: int

reveal_type(Foo.__dataclass_fields__) # revealed: dict[str, Field[Any]]
reveal_type(fields(Foo)) # revealed: tuple[Field[Any], ...]
```

## Other special cases

### `dataclasses.dataclass`
Expand Down
13 changes: 13 additions & 0 deletions crates/ty_python_semantic/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2939,6 +2939,19 @@ impl<'db> Type<'db> {
))
.into()
}
Type::ClassLiteral(class)
if name == "__dataclass_fields__" && class.dataclass_params(db).is_some() =>
{
// Make this class look like a subclass of the `DataClassInstance` protocol
Symbol::bound(KnownClass::Dict.to_specialized_instance(
db,
[
KnownClass::Str.to_instance(db),
KnownClass::Field.to_specialized_instance(db, [Type::any()]),
],
))
.with_qualifiers(TypeQualifiers::CLASS_VAR)
}
Type::BoundMethod(bound_method) => match name_str {
"__self__" => Symbol::bound(bound_method.self_instance(db)).into(),
"__func__" => {
Expand Down
20 changes: 15 additions & 5 deletions crates/ty_python_semantic/src/types/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1958,6 +1958,8 @@ pub enum KnownClass {
// backported as `builtins.ellipsis` by typeshed on Python <=3.9
EllipsisType,
NotImplementedType,
// dataclasses
Field,
}

impl<'db> KnownClass {
Expand Down Expand Up @@ -2037,7 +2039,8 @@ impl<'db> KnownClass {
// and raises a `TypeError` in Python >=3.14
// (see https://docs.python.org/3/library/constants.html#NotImplemented)
| Self::NotImplementedType
| Self::Classmethod => Truthiness::Ambiguous,
| Self::Classmethod
| Self::Field => Truthiness::Ambiguous,
}
}

Expand Down Expand Up @@ -2108,7 +2111,8 @@ impl<'db> KnownClass {
| Self::VersionInfo
| Self::EllipsisType
| Self::NotImplementedType
| Self::UnionType => false,
| Self::UnionType
| Self::Field => false,
}
}

Expand Down Expand Up @@ -2181,6 +2185,7 @@ impl<'db> KnownClass {
}
}
Self::NotImplementedType => "_NotImplementedType",
Self::Field => "Field",
}
}

Expand Down Expand Up @@ -2405,6 +2410,7 @@ impl<'db> KnownClass {
| Self::DefaultDict
| Self::Deque
| Self::OrderedDict => KnownModule::Collections,
Self::Field => KnownModule::Dataclasses,
}
}

Expand Down Expand Up @@ -2464,7 +2470,8 @@ impl<'db> KnownClass {
| Self::ABCMeta
| Self::Super
| Self::NamedTuple
| Self::NewType => false,
| Self::NewType
| Self::Field => false,
}
}

Expand Down Expand Up @@ -2526,7 +2533,8 @@ impl<'db> KnownClass {
| Self::Super
| Self::UnionType
| Self::NamedTuple
| Self::NewType => false,
| Self::NewType
| Self::Field => false,
}
}

Expand Down Expand Up @@ -2596,6 +2604,7 @@ impl<'db> KnownClass {
Self::EllipsisType
}
"_NotImplementedType" => Self::NotImplementedType,
"Field" => Self::Field,
_ => return None,
};

Expand Down Expand Up @@ -2647,7 +2656,8 @@ impl<'db> KnownClass {
| Self::UnionType
| Self::GeneratorType
| Self::AsyncGeneratorType
| Self::WrapperDescriptorType => module == self.canonical_module(db),
| Self::WrapperDescriptorType
| Self::Field => module == self.canonical_module(db),
Self::NoneType => matches!(module, KnownModule::Typeshed | KnownModule::Types),
Self::SpecialForm
| Self::TypeVar
Expand Down
Loading