python / python/mypy

Overloaded generic constructors can cause spurious errors in class methods

Open
#7,935 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal topic-overloads topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

This fails, while it shouldn't:

from typing import TypeVar, Generic, overload

T = TypeVar('T')

class C(Generic[T]):
    @overload
    def __new__(cls) -> C[None]: ...
    @overload
    def __new__(cls, item: T) -> C[T]: ...
    def __new__(cls, item=None):
        ...
    @classmethod
    def f(cls, x: T) -> T:
        return x

C.f(42)  # Argument 1 to "f" of "C" has incompatible type "int"; expected "None"

I think the same also will happen with __init__(). The problem is because the return type of the first overload is always passed as an instance type to analyze_class_attribute_access().

Note: enabling test case testGenericClassInGenericFunctionOverloadedConstructor is blocked on this.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at analyze_class_attribute_access() and reproduce the overloaded generic constructor case shown in the issue. Investigate why the first overload's return type is used as the instance type, then check the related init behavior. Enable testGenericClassInGenericFunctionOverloadedConstructor and confirm that the spurious class-method error no longer occurs.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.