Different error code when assigning the result of a function to an annotated field
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
playground: https://mypy-play.net/?mypy=latest&python=3.12&gist=8c0d1a3a8e3f444fc12af3f803e18c59
from typing import Callable, TypeVar
_T = TypeVar("_T")
def Field(default_factory: Callable[[], _T]) -> _T: ... # type: ignore[empty]
def new_list() -> list[int]:
return []
class Model:
a: list[str] = Field(default_factory=new_list)
b: int = Field(default_factory=new_list)
The error for a is:
Argument "default_factory" to "Field" has incompatible type "Callable[[], list[int]]"; expected "Callable[[], list[str]]" [arg-type]
While the error for b is:
Incompatible types in assignment (expression has type "list[int]", variable has type "int") [assignment]
The error for b seems to be more correct/less confusing. Am I missing anything?
- Mypy version used: 1.12.0
- Mypy command-line flags: N/A
- Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: 3.12
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked mypy-play reproduction and compare the diagnostics produced for fields a and b. Trace how the annotated assignments and the Field call are analyzed, then check existing diagnostic tests for argument-type and assignment errors. Done means the behavior is clarified and the reported error is consistent with the intended type-checking rule.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100