How to type hint a TypeVar that can be either bound to A
or to list[A]
#1259
Answered
by
sobolevn
randolf-scholz
asked this question in
Q&A
-
I don't quite understand why the example below fails, and how to fix it. Isn't from typing import *
class A: pass
class B(A): pass
Z = TypeVar("Z", bound=A | list[A])
class Foo(Generic[Z]):
inst_or_list: Z
def __init__(self, x: Z):
self.inst_or_list = x
a_inst: Foo[A] = Foo(A()) # ✔
a_list: Foo[list[A]] = Foo([A(), A()]) # ✔
b_inst: Foo[B] = Foo(B()) # ✔
b_list: Foo[list[A]] = Foo([B(), B()]) # ✔
test: Foo[list[B]] = Foo([B(), B()]) # ✘ raises type-var error |
Beta Was this translation helpful? Give feedback.
Answered by
sobolevn
Sep 19, 2022
Replies: 1 comment
-
No, |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
randolf-scholz
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No,
List
in Python is invariant: https://mypy.readthedocs.io/en/stable/common_issues.html#invariance-vs-covariance