Lets consider this source code:
fromtypingimportTuple, TypeVarimportcollectionsN=collections.namedtuple("N", "name")
T=TypeVar("T", N, Tuple[N, N])
# T = TypeVar("T", N, Tuple[N, ...])defget_name_bad(item: T) ->str:
returnitem.nameifisinstance(item, N) elseitem[0].namedefget_name_good(item: T) ->str:
ifisinstance(item, N):
returnitem.namereturnitem[0].namefoo=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.
Lets consider this source code:
I am using Python 3.8.3 and mypy 0.782. Depending on
TypeVardefinition I get following results:This means the conditional expression containing
isinstance()in functionget_name_bad()does trigger error while normal if-block withisinstance()fromget_name_good()doesnt. All of this is happening only with fixed-length tuple inTypeVarand not with variable length tuple.I would expect there is no difference between
Tuple[N, N]andTuple[N, ...]when checking the type viaisinstance()in conditional expression.