Skip to content

Invalid argument to fields from dataclasses #92

@my1e5

Description

@my1e5

Summary

When using fields from dataclasses, ty gives a lint:invalid-argument-type error.

https://play.ty.dev/331a08e9-3adf-41f4-a4a5-483a964a1b64

from dataclasses import dataclass, fields


@dataclass
class Foo:
    x: int
    y: float
    z: str


for field in fields(Foo):
    print(field.name, field.type)
$ uvx ty check foo.py 
error: lint:invalid-argument-type: Argument to this function is incorrect
  --> foo.py:11:21
   |
11 | for field in fields(Foo):
   |                     ^^^ Expected `DataclassInstance`, found `Literal[Foo]`
12 |     print(field.name, field.type)
   |
info: Function defined here
   --> stdlib\dataclasses.pyi:220:5
    |
218 |     ) -> Any: ...
219 |
220 | def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]: ...
    |     ^^^^^^ -------------------------------------------------------------- Parameter declared here
221 |
222 | # HACK: `obj: Never` typing matches if object argument is using `Any` type.
    |

There is a similar error for fields from attrs:

from attrs import define, fields


@define
class Foo:
    x: int
    y: float
    z: str


for field in fields(Foo):
    print(field.name, field.type)
$ uvx ty check foo.py
error: lint:invalid-argument-type: Argument to this function is incorrect
  --> foo.py:11:21
   |
11 | for field in fields(Foo):
   |                     ^^^ Expected `type[AttrsInstance]`, found `Literal[Foo]`
12 |     print(field.name, field.type)
   |
info: Function defined here
   --> .venv\Lib\site-packages\attr\__init__.pyi:311:5
    |
309 |     unsafe_hash: bool | None = ...,
310 | ) -> Callable[[_C], _C]: ...
311 | def fields(cls: type[AttrsInstance]) -> Any: ...
    |     ^^^^^^ ------------------------ Parameter declared here
312 | def fields_dict(cls: type[AttrsInstance]) -> dict[str, Attribute[Any]]: ...
313 | def validate(inst: AttrsInstance) -> None: ...
    |

Found 1 diagnostic

Version

ty 0.0.0-alpha.5 (ff90008 2025-05-06)

Metadata

Metadata

Labels

bugSomething isn't workingdataclassesIssues relating to dataclasses and dataclass_transformhelp wantedContributions especially welcome

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions