Skip to content

Overly restrictive narrowing of TypeVar via isinstance #13956

Closed as not planned
Closed as not planned

Description

@huguesb

Bug Report

When a value whose type is a TypeVar is tested via isinstance, mypy so aggressively narrows types that it refuses to let them be broadened back to the original TypeVar, even when the value is untouched.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.10&gist=ac798d8bf4d5a39d1446d86bd5c30cf3

from typing import TypeVar

T = TypeVar('T')

def foo(t: T) -> T:
  if isinstance(t, str):
      return t + "."
  elif isinstance(t, dict):
      return t
  elif isinstance(t, list):
      return t
  else:
    return t

Expected Behavior

no type errors

Actual Behavior

main.py:8: error: Incompatible return value type (got "str", expected "T")
main.py:10: error: Incompatible return value type (got "Dict[Any, Any]", expected "T")
main.py:12: error: Incompatible return value type (got "List[Any]", expected "T")
Found 3 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.971 (reproduces in all versions I've tried in the playground)
  • Mypy command-line flags: N/A
  • Python version used: 3.7 (reproduces in all versions I've tried in the playground)

Activity

  1. changed the title [-]Overly restrictive narrowing of typevar[/-] [+]Overly restrictive narrowing of TypeVar via isinstance[/+] on Oct 28, 2022
  2. tmke8 commented on Oct 28, 2022

    @tmke8
    Contributor

    Same as #12800?

  3. kmillikin commented on Oct 28, 2022

    @kmillikin

    The second and third errors do look like bugs. The type of t after isinstance(t, dict) should be revealed as <subclass of "T" and "Dict[Any, Any]"> and it should be OK to return this as a value of type T.

    The first one is more subtle. After isinstance(t, str) the type of t should be revealed as <subclass of "T" and "str">. But the string concatenation operator returns a str and T might actually be a subtype of str, so it's not necessarily OK to return that as a value of type T.

  4. hauntsaninja commented on Jan 10, 2023

    @hauntsaninja
    Collaborator

    Closing as duplicate of #10817

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