Skip to content

TypeVar("T") can be anything, unless a type guard hints at something else #16742

@alexei

Description

@alexei

Bug Report

According to the docs, a TypeVar("T") can be anything, but type guards hint at something.

To Reproduce

from typing import TypeVar


PT = TypeVar("PT")


def f(p: PT) -> PT:
    reveal_type(p)  # Revealed type is "PT`-1"

    if isinstance(p, bool):
        reveal_type(p)  # Revealed type is "builtins.bool"
        return p
    
    if isinstance(p, int):
        reveal_type(p)  # Revealed type is "builtins.int"
        return p
    
    reveal_type(p)  # Revealed type is "PT`-1"
    
    return p


f(False)  # Incompatible return value type (got "bool", expected "PT")
f(0)  # Incompatible return value type (got "int", expected "PT")
f(.0)

See https://gist.github.com/mypy-play/72f6621d0539aae2d7a3483ce389919d

Expected Behavior

I would expect the above example to pass. But then again, I've opened tickets in the past which proved to be either my own misunderstanding or my own misuse :)

Actual Behavior

main.py:8: note: Revealed type is "PT`-1"
main.py:11: note: Revealed type is "builtins.bool"
main.py:12: error: Incompatible return value type (got "bool", expected "PT")  [return-value]
main.py:15: note: Revealed type is "builtins.int"
main.py:16: error: Incompatible return value type (got "int", expected "PT")  [return-value]
main.py:18: note: Revealed type is "PT`-1"
Found 2 errors in 1 file (checked 1 source file)

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