解压缩Python的类型注释 [英] Unpacking Python's Type Annotations
问题描述
我正在尝试通过使用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的类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!