Skip to content

DocTests for functools.cache()-decorated functions have no line number #136914

@dlax

Description

@dlax

Bug report

Bug description:

(edited to reflect discussion comments)

doctests of functions decorated with functools.cache (or lru_cache()) do not get their line number retrieved, e.g.:

# file /tmp/t.py
import functools

@functools.cache
def f(x):
   """cached

   >>> f(1)
   -2
   """
   return -x
$ python -m doctest /tmp/t.py
**********************************************************************
File "/tmp/t.py", line ?, in t.f
Failed example:
    f(1)
Expected:
    -2
Got:
    -1
**********************************************************************
1 item had failures:
   1 of   1 in t.f
***Test Failed*** 1 failure.

where we can see that the File "..." line is missing the line number of the example.
Also:

>>> import doctest
>>> import t
>>> dt, = doctest.DocTestFinder().find(t)
>>> dt
<DocTest t.f from /home/denis/src/cpython/t.py:None (1 example)>
>>> print(dt.lineno)
None

This is because DocTest._find_lineno() relies on inspect.isfunction() to possibly inspect function's code and get line numbers; but inspect.isfunction() returns False for a function decorated with functools.cache because only plain types.FunctionType is considered.

Original question: Should such cached functions be considered as well in inspect.isfunction()?

I would be happy to work on a fix in case this change is acceptable.

CPython versions tested on:

CPython main branch, 3.13

Operating systems tested on:

No response

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