本文介绍了是否可以通过 doctest 测试使用 get_type_hints 的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数使用 typing.get_type_hints代码>
.我想给它添加一个文档测试.但是,看起来 get_type_hints 无法解析 doctest 中定义的类型.
I have a function that uses typing.get_type_hints
. I want to add a documentation test to it. However, it looks like get_type_hints fails to resolve types that are defined in a doctest.
这是一个简化的例子:
import typing
def f(clazz):
"""
>>> class MyClass:
... my_field: 'MyClass'
>>> f(MyClass)
"""
typing.get_type_hints(clazz)
当使用 python3 -m doctest test.py
运行它时,它抛出 NameError: name 'MyClass' is not defined
.
When running it with python3 -m doctest test.py
it throws NameError: name 'MyClass' is not defined
.
推荐答案
from __future__ import annotations
import typing
def f(clazz):
"""
>>> test = 1
>>> class MyClass:
... my_field:'MyClass'
>>> f(MyClass)
"""
typing.get_type_hints(clazz)
在文件的开头添加from __future__ import annotations
,它在python3.7上对我有用
add from __future__ import annotations
at the beginning of the file, it work for me on python3.7
这篇关于是否可以通过 doctest 测试使用 get_type_hints 的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!