python - 为什么在 Python 中不允许单一类型约束?

标签 python types python-3.6

假设你想约束一个类型变量来实现某个接口(interface)。你可以这样写:

from typing import TypeVar, Callable

T = TypeVar('T', Callable)

class Foo(Generic[T]):
    ...

>> TypeError: A single constraint is not allowed

为什么 Python 对这种类型约束的使用不满意? PEP 484Python source code在这方面没有帮助。

注意:在我的特定情况下,我对约束类型变量以实现抽象基类很感兴趣,但原理是相同的。

最佳答案

您正在寻找 bound :

T = TypeVar('T', bound=Callable)

来自 the docs :

a type variable may specify an upper bound using bound=<type>. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type, see PEP 484.

TypeVar(name, *args)意味着类型必须是 args 之一, 所以 T 的所有实例只能由 Callable 替换如果T = TypeVar('T', Callable)被允许。

你应该能看出这里的区别(虽然我没有真正尝试过,呵呵):

from typing import Generic, TypeVar, Callable

T = TypeVar('T', Callable, bool)

class Foo(Generic[T]):
    value: T

    def __init__(self, value: T) -> None:
        self.value = value

class Bar:
    baz = 5

    def __call__(self):
        pass

f = Foo(Bar())
print(f.value.baz)  # doesn’t typecheck because f.value is only a Callable

关于python - 为什么在 Python 中不允许单一类型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185027/

相关文章:

python - 按另一列的顺序对包含 NA 的一列中的值进行排序

python - 按下按钮时更新 Tkinter 中的标签

Python替换字符串中的3个随机字符,不重复

haskell - return >=> f 在 Haskell 中如何工作?

python - mypy 找不到模块 'dropbox'

python - 为什么输出会是11032? Python3.6

python - 将函数内的多值字典返回为漂亮的格式

python - 在 Python 中从 FASTA 制作 Blast 数据库

types - 如何解决UiFrame::getConfiguration()的 “No match for =( TagGroup, RealNumber )”错误

python - python-3.6 中带有 'f' 前缀的字符串