Skip to content

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

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

Closed
Redoubts opened this issue May 29, 2025 · 3 comments · Fixed by #19183
Closed

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

Redoubts opened this issue May 29, 2025 · 3 comments · Fixed by #19183
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder

Comments

@Redoubts
Copy link

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
@Redoubts Redoubts added the bug mypy got something wrong label May 29, 2025
@hauntsaninja
Copy link
Collaborator

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

@hauntsaninja
Copy link
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

@hauntsaninja hauntsaninja 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 May 29, 2025
@ilevkivskyi
Copy link
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
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants