简体   繁体   English

Python 将类型提示字符串表示(从文档字符串)转换为实际类型/键入 object

[英]Python convert type hint string representation (from docstring) to actual type/typing object

I would like to know if there is an existing implementation that converts the string representation of a type hint (eg from a docstring) back to the type (or typing) object.我想知道是否存在将类型提示的字符串表示(例如,从文档字符串)转换回类型(或键入)object 的现有实现。 Thereby arbitrary deep nested types should also be supported (see third example).因此,还应该支持任意深度嵌套类型(参见第三个示例)。

import typing import List, Optional, Union

converter_function("List[str]") == List[str]

converter_function("int") == int

converter_function("Optional[List[Union[str, float]]]") == Optional[List[Union[str,float]]]

converter_function("foobar") # Exception / None

One option would be to simply use eval, but I would like to avoid that at all costs:D一种选择是简单地使用 eval,但我想不惜一切代价避免这种情况:D

Edit As background on why I want to do this: I want to write a script that checks if a docstring matches 100% to a function, all types are correct and so on.编辑作为我为什么要这样做的背景:我想编写一个脚本来检查文档字符串是否与 function 匹配 100%,所有类型都正确等等。

The closest thing I can find (except for eval of course) is typing.get_type_hints .我能找到的最接近的东西(当然eval除外)是typing.get_type_hints If your functions are properly type annotated, then typing.get_type_hints can resolve the annotations.如果您的函数正确地进行了类型注释,那么typing.get_type_hints可以解析注释。 It works for string annotations, arbitrarily nested types, and generic types;它适用于字符串注解、任意嵌套类型和泛型类型; basically any valid annotations.基本上任何有效的注释。 For example:例如:

from typing import List, Optional, Union, get_type_hints

def my_func(a: "List[str]", b: "int") -> "Optional[List[Union[str, float]]]":
    pass

print(get_type_hints(my_func))

you'd get你会得到

{'a': typing.List[str],
 'b': <class 'int'>,
 'return': typing.Optional[typing.List[typing.Union[str, float]]]}

Internally, get_type_hints converts the strings into typing.ForwardRef s and then evaluate them.在内部, get_type_hints将字符串转换为typing.ForwardRef ,然后评估它们。 These are private APIs so they might not be stable across Python versions, but if you only have the annotation strings but not a function, you might try this out:这些是私有 API,因此它们在 Python 版本中可能不稳定,但如果您只有注释字符串但没有 function,您可以试试这个:

>>> from typing import ForwardRef, _eval_type

>>> _eval_type(ForwardRef("Optional[List[Union[str, float]]]"), globals(), globals())
typing.Optional[typing.List[typing.Union[str, float]]]

but at this point, you might be better off with eval :P但在这一点上,你可能会更好eval :P

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

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