Is it possible to test a function that uses get_type_hints with a doctest?

时光毁灭记忆、已成空白 提交于 2019-12-08 12:37:22

问题


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.

Here is a simplified example:

import typing

def f(clazz):
    """
    >>> class MyClass:
    ...   my_field: 'MyClass'
    >>> f(MyClass)
    """
    typing.get_type_hints(clazz)

When running it with python3 -m doctest test.py it throws NameError: name 'MyClass' is not defined.


回答1:


from __future__ import annotations

import typing


def f(clazz):
    """
    >>> test = 1
    >>> class MyClass:
    ...   my_field:'MyClass'
    >>> f(MyClass)
    """
    typing.get_type_hints(clazz)

add from __future__ import annotations at the beginning of the file, it work for me on python3.7



来源:https://stackoverflow.com/questions/55937472/is-it-possible-to-test-a-function-that-uses-get-type-hints-with-a-doctest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!