Skip to content

TypeVar resolved to a concrete type using isinstance causes mypy to become confused at the equivalence #11664

Closed
@alexkoay

Description

@alexkoay

Bug Report

To Reproduce

from typing import Any, Generic, TypeVar
T = TypeVar("T")

class Foo(Generic[T]):
    def __init__(self, value: T):
        self.value = value

def identity(value: T) -> Foo[T]:
    if isinstance(value, str):
        return Foo(value)
    return Foo(value)

Expected Behavior

mypy should be able to tell that in the type-guarded block, T == str and use that to qualify the types.

Actual Behavior

mypy reports an error Argument 1 to "Foo" has incompatible type "str"; expected "T" in the type-guarded block in identity().

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.9
  • Operating system and version: Windows 10

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