Python 键入:键入文字

Python Typing: Type literal

我正在编写一个函数,它接受类型为 type 的参数 dtype,如下所示。

def my_function(dtype: type):
    pass

有没有办法将dtype的值限制为strint?类型联合 str | int 不会完成这项工作,因为它将被解释为 dtype 可以有一个值 with type str or int,事实并非如此。

此外,我可能不想断言 dtype 的值,因为 mypy 似乎不太适合它。

def my_function(dtype: type):
    assert dtype == str or dtype == int

这个问题有解决方法吗?

好的,我要post答案以备将来参考。非常感谢 juanpa.arrivillaga 的解决方案!

我们can use the generic Type[T]typing模块中引用一个文字类型,如下所示。

from typing import Type


def my_function(dtype: Type[str] | Type[int]):
    pass

或从Python 3.9开始,builtins.type现在支持type[T]泛型,如PEP 585所述。

def my_function(dtype: type[str] | type[int]):
    pass