是否可以通过doctest测试使用get_type_hints的函数? [英] Is it possible to test a function that uses get_type_hints with a doctest?

查看:95
本文介绍了是否可以通过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.

推荐答案

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的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆