Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
twoertwein opened this issue Aug 20, 2022 · 1 comment · Fixed by #19183
Closed

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

twoertwein opened this issue Aug 20, 2022 · 1 comment · Fixed by #19183
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code topic-type-narrowing Conditional type narrowing / binder

Comments

@twoertwein
Copy link

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
@twoertwein twoertwein added the bug mypy got something wrong label Aug 20, 2022
@AlexWaygood AlexWaygood added false-positive mypy gave an error on correct code topic-type-narrowing Conditional type narrowing / binder labels Aug 20, 2022
@kellerza
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants