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

AnyStr parameter + sys.version_info check in function causes mypy to not realize True is bool #18210

Closed
jwodder opened this issue Nov 29, 2024 · 1 comment · Fixed by #18217
Closed
Assignees
Labels
bug mypy got something wrong topic-type-variables

Comments

@jwodder
Copy link

jwodder commented Nov 29, 2024

Bug Report

Consider the following code:

from __future__ import annotations
import sys
from typing import AnyStr


def foo(s: AnyStr) -> bool:
    if sys.version_info >= (4, 42):  # Something that won't be matched on any extant Python
        return True
    return False

Running mypy --warn-return-any on this code produces the following erroneous error:

bool04.py:8: error: Returning Any from function declared to return "bool"  [no-any-return]
Found 1 error in 1 file (checked 1 source file)

If the type of the s parameter is changed to str, or the parameter is removed entirely, then the error goes away. The error also goes away if the sys.version_info check is something that succeeds on the current Python.

Expected Behavior

mypy should not have reported any errors.

Your Environment

  • Mypy version used: 1.13.0
  • Mypy command-line flags: --warn-return-any
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: observed on Python 3.8.20, Python 3.9.20, Python 3.12.7, and Python 3.13.0
@jwodder jwodder added the bug mypy got something wrong label Nov 29, 2024
@brianschubert
Copy link
Collaborator

brianschubert commented Nov 30, 2024

Can confirm that the required ingredients are an always-false sys.version_info check (or similar, not TYPE_CHECKING also works) and a constrained TypeVar.

Even funkier:

T  = TypeVar("T", int, str)

def foo(x: T) -> bool:
    if sys.version_info >= (4, 42):
        x = "foo"
        return True  # E: Incompatible return value type (got "str", expected "bool")
    return False

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-variables
Projects
None yet
2 participants