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

dataclasses.asdict definition is not correct #8518

Open
sobolevn opened this issue Aug 10, 2022 · 3 comments
Open

dataclasses.asdict definition is not correct #8518

sobolevn opened this issue Aug 10, 2022 · 3 comments
Labels
stubs: false positive Type checkers report false errors

Comments

@sobolevn
Copy link
Member

sobolevn commented Aug 10, 2022

Example:

from dataclasses import dataclass, asdict

@dataclass
class D:
    x: int

asdict(D(1), dict_factory=dict)  # Argument "dict_factory" to "asdict" has incompatible type "Type[Dict[Any, Any]]"; expected "Callable[[List[Tuple[str, Any]]], Dict[_KT, _VT]]"

But, since dict is used a default implementation, it should be valid.
Source: https://github.com/python/cpython/blob/325ae93b6b7113cd4a4c2ce441615ae7def779e2/Lib/dataclasses.py#L1254

Found in python/mypy#13367

@AlexWaygood AlexWaygood added the stubs: false positive Type checkers report false errors label Aug 10, 2022
@sobolevn
Copy link
Member Author

sobolevn commented Aug 10, 2022

Changing list to Iterable does not work as well:

from dataclasses import dataclass, astuple, asdict

@dataclass
class D:
    x: int

from typing import Callable, Any, TypeVar, Iterable, Tuple
_T = TypeVar('_T')
def asdict2(obj: Any, *, dict_factory: Callable[[Iterable[Tuple[str, Any]]], _T]) -> _T: ...

asdict2(D(3), dict_factory=dict)  #  error: Argument "dict_factory" to "asdict2" has incompatible type "Type[Dict[Any, Any]]"; expected "Callable[[Iterable[Tuple[str, Any]]], Dict[_KT, _VT]]"
@5tefan
Copy link

5tefan commented Sep 9, 2022

As a workaround, I have noticed that annotating the return value will succeed with mypy.

from typing import Any, Dict
from dataclasses import dataclass, asdict

@dataclass
class D:
    x: int

out: Dict[str, Any] = asdict(D(1), dict_factory=dict)  # Success: no issues found in 1 source file
@max-muoto
Copy link
Contributor

@sobolevn Both examples work in MyPy/Pyright now, I'm assuming this can be closed out?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: false positive Type checkers report false errors
4 participants