【问题标题】:Is it possible to test a function that uses get_type_hints with a doctest?是否可以通过 doctest 测试使用 get_type_hints 的函数?
【发布时间】:2019-09-20 02:11:55
【问题描述】:

我有一个使用typing.get_type_hints 的函数。我想给它添加一个documentation test。但是,get_type_hints 似乎无法解析 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

【问题讨论】:

    标签: python annotations doctest type-hinting


    【解决方案1】:
    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

    【讨论】:

    • 确实有效。谢谢 !这是打字模块中的错误吗?
    • 我还想知道为什么my_field:'MyClass' 在 doctest 中不起作用,它在 doctest 中具有不同的行为,而不是。在 doctest 中,新语法似乎还没有准备好。
    • 不幸的是,PEP563注解似乎也存在问题:gist.github.com/lovasoa/74ea62a89f5bf073b0e0c2f222008ae3
    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    相关资源
    最近更新 更多