本文介绍了解压 Python 的类型注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 inspect 模块中的 signature() 函数,根据我在一些 Python 函数中提供的类型注释生成一些 JavaScript.

I'm trying to generate some JavaScript based on the type annotations I have provided in on some Python functions by using the signature() function in the inspect module.

当类型是一个简单的内置类时,这部分按我的预期工作:

This part works as I expect when the type is a simple builtin class:

import inspect

def my_function() -> dict:
    pass

signature = inspect.signature(my_function)
signature.return_annotation is dict  # True

虽然我不确定如何打开和检查更复杂的注释,例如:

Though I'm not sure how to unwrap and inspect more complex annotations e.g:

from typing import List
import inspect

def my_function() -> List[int]:
    pass

signature = inspect.signature(my_function)
signature.return_annotation is List[int]  # False

前向引用自定义类再次出现类似问题:

Again similar problem with forward referencing a custom class:

def my_function() -> List['User']:
    pass
...
signature.return_annotation  # typing.List[_ForwardRef('User')]

我希望得到的结果是这样的 - 这样我就可以在生成 JavaScript 时进行适当的分支:

What I'm looking to get out is something like this - so I can branch appropriately while generating the JavaScript:

type = signature.return_annotation... # list
member_type = signature.return_annotation... # int / 'User'

谢谢.

推荐答案

Python 3.8 为此提供了 typing.get_origin()typing.get_args() !>

Python 3.8 provides typing.get_origin() and typing.get_args() for this!

assert get_origin(Dict[str, int]) is dict
assert get_args(Dict[int, str]) == (int, str)

assert get_origin(Union[int, str]) is Union
assert get_args(Union[int, str]) == (int, str)

参见 https://docs.python.org/3/library/typing.html#typing.get_origin

这篇关于解压 Python 的类型注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:48