首页 文章

在Python中禁止TypeVar的特定类型

提问于
浏览
0

是否有任何方法可以使 Python TypeVarnot allowed 绑定到 some types

我知道你可以将TypeVar限制为某些类型,有一个上限或将其标记为covariant / contravariant / invariant,但似乎没有办法说“TypeVar不允许这些类型” .

基本上我想说的是像C中的 std::enable_if_t<!std::is_base_of_v<NotAllowedType, T>> .

例如,T永远不应该是例外:

from typing import Union, Generic, TypeVar


T = TypeVar('T')


class Expected(Generic[T]):
    def __init__(self, value_or_error: Union[T, Exception]):
        self._value_or_error = value_or_error

    def is_valid(self) -> bool:
        return not isinstance(self._value_or_error, Exception)

但实现这一目标并没有一种直截了当的方式 . 据我所知,大多数泛型(例如Java,Scala,Kotlin)不支持这一点,但也许我错过了某些内容或者有一个解决方法(?) .

1 回答

相关问题