Skip to content

Wrong type narrowing when using type without an argument in isinstance call #13462

Closed

Description

@twoertwein

To Reproduce

from typing import TypeVar

T = TypeVar("T")


def fun(x: T, klass: type) -> T:
    if not isinstance(x, klass):
        raise TypeError
    return x

Expected Behavior

No error.

Actual Behavior

error: Incompatible return value type (got "object", expected "T") [return-value]

Your Environment

  • Mypy version used: 0.971

Activity

  1. kellerza commented on Jul 25, 2024

    @kellerza

    Adding a constraint to the TypeVar seems to help

    T = TypeVar("T", str, str)
    
    def fun(val: T) -> T:
        if not isinstance(val, str):
            raise TypeError
        return val
  2. pkit commented on Aug 16, 2025

    @pkit

    @ilevkivskyi How exactly #19183 closed this one?
    I still see the same error in the pretty brain dead scenarios.

        def rename_deep(self, data: T, col_map: dict[str, str]) -> T:
            if isinstance(data, str):
                return self.rename_all(data, col_map)
            if isinstance(data, dict):
                return {key: self.rename_deep(value, col_map) for key, value in data.items()}
            if isinstance(data, list):
                return [self.rename_deep(item, col_map) for item in data]
            return data
    
    error: Incompatible return value type (got "str", expected "T")  [return-value]
    error: Incompatible return value type (got "dict[Any, Any]", expected "T")  [return-value]
    error: Incompatible return value type (got "list[Any]", expected "T")  [return-value]
    

    Using mypy 1.17.1 which should include #19183

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 wrongfalse-positivemypy gave an error on correct codetopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions