Skip to content
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

Weird behaviour with TypeVar and conditional expression containing isinstance() #9195

Open
ghost opened this issue Jul 23, 2020 · 1 comment
Labels
bug mypy got something wrong topic-ternary-expression a if b else c topic-type-narrowing Conditional type narrowing / binder topic-type-variables

Comments

@ghost
Copy link

ghost commented Jul 23, 2020

Lets consider this source code:

from typing import Tuple, TypeVar
import collections

N = collections.namedtuple("N", "name")
T = TypeVar("T", N, Tuple[N, N])
# T = TypeVar("T", N, Tuple[N, ...])


def get_name_bad(item: T) -> str:
    return item.name if isinstance(item, N) else item[0].name


def get_name_good(item: T) -> str:
    if isinstance(item, N):
        return item.name
    return item[0].name


foo = N("1")
bar = N("2")
both = (foo, bar)

get_name_good(foo)
get_name_good(bar)
get_name_good(both)

get_name_bad(foo)
get_name_bad(bar)
get_name_bad(both)

I am using Python 3.8.3 and mypy 0.782. Depending on TypeVar definition I get following results:

$ grep "^T = TypeVar" snippet.py 
T = TypeVar("T", N, Tuple[N, N])
$ mypy-3.8 snippet.py 
snippet.py:12: error: "Tuple[N, N]" has no attribute "name"
Found 1 error in 1 file (checked 1 source file)
$ grep "^T = TypeVar" snippet.py 
T = TypeVar("T", N, Tuple[N, ...])
$ mypy-3.8 snippet.py 
Success: no issues found in 1 source file

This means the conditional expression containing isinstance() in function get_name_bad() does trigger error while normal if-block with isinstance() from get_name_good() doesnt. All of this is happening only with fixed-length tuple in TypeVar and not with variable length tuple.

I would expect there is no difference between Tuple[N, N] and Tuple[N, ...] when checking the type via isinstance() in conditional expression.

@hauntsaninja
Copy link
Collaborator

Seems similar to #4134

@AlexWaygood AlexWaygood added bug mypy got something wrong topic-type-variables topic-ternary-expression a if b else c topic-type-narrowing Conditional type narrowing / binder labels Mar 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-ternary-expression a if b else c topic-type-narrowing Conditional type narrowing / binder topic-type-variables
Projects
None yet
Development

No branches or pull requests

2 participants