Skip to content

Generic type inference incorrectly handled in edge case #13921

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

Open
zevbo opened this issue Oct 19, 2022 · 4 comments
Open

Generic type inference incorrectly handled in edge case #13921

zevbo opened this issue Oct 19, 2022 · 4 comments
Labels
bug mypy got something wrong

Comments

@zevbo
Copy link

zevbo commented Oct 19, 2022

Bug Report

If you try to widdle down the type of a generic class in a certain manner, it only works if you use an intermediate variable. A little tough to explain without looking at the example

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.10&gist=d3ebef88a57147cef8a8d311e1b33fb7

from abc import ABC, abstractmethod
from typing import Generic, TypeVar

T = TypeVar("T")

class A(ABC, Generic[T]):

    @abstractmethod
    def t(self) -> T:
        pass

def get_a_does_work(a: A[T]) -> T:
    t_value = a.t()
    if t_value is None:
        return None 
    return a.t()

def get_a_should_work(a: A[T]) -> T:
    if a.t() is None:
        return None 
    return a.t()

Expected Behavior

Both get_a_does_work and get_a_should_work should pass type checking.

Actual Behavior

get_a_should_work outouts:
main.py:20: error: Incompatible return value type (got "None", expected "T")

Your Environment

You can see on the playground

@zevbo zevbo added the bug mypy got something wrong label Oct 19, 2022
@hauntsaninja
Copy link
Collaborator

There's no reason for mypy to believe that a.t() is deterministic

@zevbo
Copy link
Author

zevbo commented Oct 19, 2022

Shouldn't matter. If a.t() can return None, then None must be a subtype of T. Hence, it is valid to return None.

And mypy does know this, given that the first function does works fine.

@headtr1ck
Copy link

Might be related to #13956

@ilevkivskyi
Copy link
Member

Now mypy shows errors in both cases which is at least more consistent. First example used to work by accident, mypy doesn't support dependencies between expressions in general (except few common cases).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

4 participants