在 Python 中禁止 TypeVar 的特定类型

Disallow specific types for a TypeVar in Python

有什么方法可以让 Python TypeVar 不允许 绑定到 一些类型?

我知道您可以将 TypeVar 限制为某些类型,有一个上限或将其标记为 covariant/contravariant/invariant,但似乎没有办法说 "The TypeVar is not allowed to be these types" .

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

例如,T 永远不应是 Exception:

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)不支持这一点,但也许我遗漏了什么或者有解决方法(?)。

不出所料,目前似乎不支持:https://github.com/python/typing/issues/599