Skip to content

[1.16 regression] narrowing a typevar via comparison to None #19166

Closed
@Redoubts

Description

@Redoubts

Bug Report

Consider the following: https://mypy-play.net/?mypy=master&python=3.12&gist=dbad46bbd0f39d316a2e82262ceeb4fa

In 1.16, this code raises an error at the first return after the None check, Incompatible return value type (got "None", expected "T"), though it was fine in 1.15

Your Environment

  • Mypy version used: 1.16
  • Mypy command-line flags: stock
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.11, 3.12

Activity

hauntsaninja

hauntsaninja commented on May 29, 2025

@hauntsaninja
Collaborator

mypy_primer -p test.py --bisect --debug --old 'v1.15.0' says this is #18972

hauntsaninja

hauntsaninja commented on May 29, 2025

@hauntsaninja
Collaborator

Simpler repro:

from typing import Callable, TypeVar

T = TypeVar("T")


def foo(f: Callable[[], T]) -> T:
    ret = f()
    if ret is None:
        return ret
    return ret
changed the title [-]'Incompatible return value type (... expected "T")' when using param spec and `is None` in wrapped function[/-] [+][1.16 regression] narrowing a typevar via comparison to None[/+] on May 29, 2025
ilevkivskyi

ilevkivskyi commented on May 30, 2025

@ilevkivskyi
Member

I will take a look at this (hopefully during weekend). The best course of action may be to infer a type variable with upper bound None (or anything else that doesn't make a meaningful intersection with given type variable). Essentially we can do something like (very roughly) meet(T(bound=A), B) == T(bound=meet(A, B)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @Redoubts@ilevkivskyi@hauntsaninja@sterliakov

      Issue actions

        [1.16 regression] narrowing a typevar via comparison to None · Issue #19166 · python/mypy