简体   繁体   English

未检测到@cached_property doctest

[英]@cached_property doctest is not detected

I have a code.我有一个代码。 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 is a function decorated by @cached_property . test_3是一个由@cached_property修饰的函数。 It has a doctest.它有一个doctest。 but that was not executed.但这没有被执行。

$ 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.

How can I run test_3 doctest?如何运行 test_3 doctest?

Environment环境

$ python3 --version
Python 3.9.6

$ uname
Darwin

The problem is likely caused by a difference in the implementation of cache and cached_property .该问题可能是由cachecached_property的实现不同引起的。 Namely, cache sets __module__ whereas cached_property does not:即, 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'

Functions that are not defined in the current __module__ are ignored by doctesting .当前__module__中未定义的函数会被 doctesting 忽略 This is intentional since otherwise all the doctests of the methods that you import at the top of the file would run.这是有意的,否则您在文件顶部导入的方法的所有文档测试都会运行。 However, in this case, this seems like a bug to me.但是,在这种情况下,这对我来说似乎是一个错误。

One can explicitly add a method (or class) to the doctests for a module by adding it to __test__ , so in your case this should do the trick:可以通过将方法(或类)添加到__test__来显式地将方法(或类)添加到模块的文档测试中,因此在您的情况下,这应该可以解决问题:

__test__= { "C1.test_3": C1.test_3 }

To fix this in Python, one should probably add self.__module__ = func.__module__ to this initializer and maybe all the others that update_wrapper() sets for @cache .要在 Python 中解决这个问题,可能应该将self.__module__ = func.__module__这个初始化程序,也许还有 update_wrapper update_wrapper()@cache设置的所有其他人 But maybe this has unintended side effects and that's why this was not set in the first place.但也许这会产生意想不到的副作用,这就是为什么一开始没有设置它的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM