Skip to content

Doctest ignores methods decorated with functools.singledispatchmethod #129578

Open
@viccie30

Description

@viccie30

Bug report

Bug description:

Doctest does not recognize tests in the docstrings of methods decorated with functools.singledispatchmethod. There's 2 causes:

  1. It checks the dictionary of classes for functions and subclasses, thereby not invoking descriptors.

    cpython/Lib/doctest.py

    Lines 1061 to 1073 in df4a2f5

    if inspect.isclass(obj) and self._recurse:
    for valname, val in obj.__dict__.items():
    # Special handling for staticmethod/classmethod.
    if isinstance(val, (staticmethod, classmethod)):
    val = val.__func__
    # Recurse to methods, properties, and nested classes.
    if ((inspect.isroutine(val) or inspect.isclass(val) or
    isinstance(val, property)) and
    self._from_module(module, val)):
    valname = '%s.%s' % (name, valname)
    self._find(tests, val, valname, module, source_lines,
    globs, seen)
  2. functools.singledispatchmethod does not call functools.update_wrapper on its instance, only on the wrapper function returned from its __get__ method.

A similar issue for cached_property was fixed in #107996.

Example

# mwe.py
import functools

class Class:
    @functools.singledispatchmethod
    def singledispatchmethod(self, arg):
        """
        >>> print(Class().singledispatchmethod(5))
        foo
        """
        return "foo"

    def regularmethod(self, arg):
        """
        >>> print(Class().regularmethod(5))
        foo
        """
        return "foo"
$ python3 -m doctest -v mwe.py
Trying:
    print(Class().regularmethod(5))
Expecting:
    foo
ok
2 items had no tests:
    mwe
    mwe.Class
1 item passed all tests:
   1 test in mwe.Class.regularmethod
1 test in 3 items.
1 passed.
Test passed.

doctest only finds one doctest, where there should be two.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions