-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Pyright doesn't reject uses of Field
for non-dataclasses
#4980
Comments
It appears that import dataclasses
class NonDataClass:
my_list: list[int] | dataclasses.Field[list[int]] = dataclasses.field(default_factory=list)
def add_item(self, item: int) -> None:
if isinstance(self.my_list, dataclasses.Field):
assert isinstance(self.my_list.default_factory, Callable)
self.my_list = self.my_list.default_factory()
reveal_type(self.my_list)
self.my_list.append(item)
instance = NonDataClass()
instance.add_item(1)
assert instance.my_list == [1] So I think it's reasonable to expect the user to explicitly declare the union type if they want to uses a dataclass.field on a non-dataclass? |
Pyright is doing the right thing here from a type checking standpoint. Pyright does apply special-case logic for Not surprisingly, mypy also does not generate an error in this case. |
Oh my, I think it's even worse than that -- @overload
def field(
*,
default_factory: Callable[[], _T],
init: bool = True,
repr: bool = True,
hash: bool | None = None,
compare: bool = True,
metadata: Mapping[Any, Any] | None = None,
kw_only: bool = ...,
) -> _T: ... with the helpful comment:
|
Describe the bug
pyright
does not complain when adataclasses.field
is used as the default value of an attribute on a non-dataclass.To Reproduce
pyright
issues no error.Expected behavior
I should get the same error as if I used a literal of the wrong type (like
"5"
):VS Code extension or command-line
On command-line using
pyright
1.1.302 and 1.1.303.Additional context
Perhaps this behavior is by design? Maybe it's idiomatic in python to use
dataclasses.field
as a default value and do a manualisinstance(self.my_list, Field)
check in__init__
or something?The text was updated successfully, but these errors were encountered: