Skip to content

Generic type inference incorrectly handled in edge case #13921

Open
@zevbo

Description

@zevbo

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions