Python 泛型有限制吗?

Sal*_*ley 6 python type-hinting mypy python-3.8

自 Python 3.8 以来,我已经能够执行以下操作:

from typing import TypeVar, Generic

T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self) -> None:
        # Create an empty list with items of type T
        self.items: List[T] = []
Run Code Online (Sandbox Code Playgroud)

我可以是 Stack[int] 或 Stack[str],T 可以是任何东西,对吗?

但是,如果我想将 T 的可能值限制为 Foo 的子类,或者 Foo 的子类,并实现 BarProtocol,该怎么办?

Scala 有这些漂亮的协方差运算符:

T <: Foo, T <: BarProtocol
Run Code Online (Sandbox Code Playgroud)

但是 Python 中有等价的吗?