Is it possible to test a function that uses get_ty

2019-06-12 20:41发布

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条回答
倾城 Initia
2楼-- · 2019-06-12 21:31
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

查看更多
登录 后发表回答