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

Overloaded generic constructors can cause spurious errors in class methods #7935

Open
ilevkivskyi opened this issue Nov 12, 2019 · 2 comments
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal topic-overloads topic-type-variables

Comments

@ilevkivskyi
Copy link
Member

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.

@ilevkivskyi ilevkivskyi added bug mypy got something wrong topic-type-variables priority-1-normal false-positive mypy gave an error on correct code labels Nov 12, 2019
@e2t
Copy link

e2t commented Nov 26, 2019

I have the same question.

from typing import TypeVar, Generic

T = TypeVar('T', int, float)

class Aaa(Generic[T]):
    def __init__(self, value: T):
        pass

class Bbb(Aaa[T]):
    def __init__(self, value: T):
        super().__init__(value)

mypy reports about last line:

Argument 1 to "__init__" of "Aaa" has incompatible type "int"; expected "T"
Argument 1 to "__init__" of "Aaa" has incompatible type "float"; expected "T"

Why?

@ilevkivskyi
Copy link
Member Author

I think this is a different issue, see last example in #5416

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal topic-overloads topic-type-variables
Projects
None yet
Development

No branches or pull requests

3 participants