简体   繁体   English

Python 打字:字面量

[英]Python Typing: Type literal

I am writing a function that takes an argument dtype of type type as shown below.我正在编写一个 function,它采用类型type的参数dtype ,如下所示。

def my_function(dtype: type):
    pass

Is there a way to restrict the value of dtype only to str and int ?有没有办法将dtype的值限制为strint The type union str | int类型 union str | int str | int will not do the job because it will then be interpreted as dtype can have a value with type str or int , which is not the case. str | int不会完成这项工作,因为它将被解释为dtype可以具有类型为strint的值,但事实并非如此。

Also, I may not want to assert the value of dtype because mypy doesn't seem to work well with it.另外,我可能不想断言mypy dtype不能很好地处理它。

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

Is there a workaround to this problem?这个问题有解决方法吗?

Ok, I'm going to post the answer for future reference.好的,我将发布答案以供将来参考。 Big thank you to juanpa.arrivillaga for the solution!非常感谢juanpa.arrivillaga提供的解决方案!

We can use the genericType[T] from the typing module to refer to a literal type, as shown below.我们可以使用typing模块中的泛型Type[T]来引用文字类型,如下所示。

from typing import Type


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

Or from Python 3.9 , builtins.type now supports the type[T] generic, as stated in PEP 585 .或者从Python 3.9开始, builtins.type现在支持type[T]泛型,如PEP 585中所述。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM