Skip to content

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

Closed as not planned

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)

Activity

  1. changed the title [-]`TypeVar("T")` can be anything, unless a type guard[/-] [+]`TypeVar("T")` can be anything, unless a type guard hints at something else[/+] on Jan 3, 2024
  2. hauntsaninja commented on Jan 4, 2024

    @hauntsaninja
    Collaborator

    Thanks for the issue, I think this is a duplicate of #15151. See also #15711 / #15377

  3. alexei commented on Jan 4, 2024

    @alexei
    Author

    If a fix isn't planned, then what is the recommended workaround? Cast to T?

  4. hauntsaninja commented on Jan 4, 2024

    @hauntsaninja
    Collaborator

    Yes, type ignore or cast will work. Definitely a bug so will be fixed

  5. alexei commented on Jan 4, 2024

    @alexei
    Author

    Ok, thanks

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 wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions