有限制的Python泛型?

有限制的Python泛型?,python,typing,mypy,python-3.8,Python,Typing,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] = [] 我可以是堆栈[int]或堆栈[str],T可以

从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] = []
我可以是堆栈[int]或堆栈[str],T可以是任何东西,对吗

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

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

T <: Foo, T <: BarProtocol

T您最好使用
TypeVar
bound
参数限制为可能类型的列表或某些类型的子类型,并使用
协变
参数指示协变/逆变这是否回答了您的问题?您所能做的就是使用
TypeVar
bound
参数将可能的类型或某些类型的子类型限制为列表,并使用
covarant
参数指示协方差/反方差这是否回答了您的问题?