@cached_property未检测到doctest。

4

我有一段代码,a.py

from functools import cached_property, cache
import doctest


class C1:

    def test_1(self):
        """
        >>> C1().test_1()
        'f'
        """
        return "f"

    @property
    def test_2(self):
        """
        >>> C1().test_2
        'p'
        """
        return "p"

    @cached_property
    def test_3(self):
        """
        >>> C1().test_3
        'cp'
        """
        return "cp"

    @cache
    def test_4(self):
        """
        >>> C1().test_4()
        'c'
        """
        return "c"


doctest.testmod()

test_3 是一个被 @cached_property 装饰的函数。 它有一个文档测试,但是并没有被执行。

$ python3 a.py -v
Trying:
    C1().test_1()
Expecting:
    'f'
ok
Trying:
    C1().test_2
Expecting:
    'p'
ok
Trying:
    C1().test_4()
Expecting:
    'c'
ok
2 items had no tests:
    __main__
    __main__.C1
3 items passed all tests:
   1 tests in __main__.C1.test_1
   1 tests in __main__.C1.test_2
   1 tests in __main__.C1.test_4
3 tests in 5 items.
3 passed and 0 failed.
Test passed.

我该如何运行test_3 doctest?

环境

$ python3 --version
Python 3.9.6

$ uname
Darwin
1个回答

3
这个问题可能是由于cachecached_property实现上的差异引起的。具体来说,cache设置了__module__,而cached_property没有设置:
>>> from functools import cache, cached_property
>>> @cache
... def f(): pass
...
>>> @cached_property
... def g(): pass
...
>>> f.__module__
'__main__'
>>> g.__module__
'functools'

当前未在__module__中定义的函数将被doctesting忽略。这是有意为之的,否则导入文件顶部的方法的所有doctests都会运行。然而,在这种情况下,我认为这似乎是一个错误。
可以通过将其添加到__test__来显式地将方法(或类)添加到模块的doctests中,所以在你的情况下,这应该可以解决问题:
__test__= { "C1.test_3": C1.test_3 }

为了在Python中解决这个问题,可能需要在这个初始化器中添加self.__module__ = func.__module__,以及update_wrapper()设置为@cache所有其他初始化器。但是可能会产生意想不到的副作用,这就是为什么一开始没有设置的原因。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接