禁止在Python中使用TypeVar的特定类型

时间:2018-12-09 20:24:05

标签: python type-hinting restriction

有什么方法可以使 Python TypeVar 不允许 绑定到某些类型

我知道您可以将TypeVar限制为某些类型,可以将其上限或将其标记为协变/相反/不变,但是似乎没有办法说“ TypeVar不允许是这些类型。”

基本上我想说的是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)都不支持此功能,但是也许我缺少了某些东西,或者有一种解决方法(?)。

1 个答案:

答案 0 :(得分:0)

如预期的那样,当前似乎不支持此功能:https://github.com/python/typing/issues/599

相关问题