sphinx-autodoc-typehints icon indicating copy to clipboard operation
sphinx-autodoc-typehints copied to clipboard

Should use annotationlib in Python 3.14 to avoid throwing exceptions when using forward references

Open ruipin opened this issue 6 months ago • 2 comments

Currently, using forward references in 3.14 without from __future__ import annotations causes exceptions to be thrown, e.g. my project pygaindalf does not work with the following exception:

Traceback
=========

      File "pygaindalf/.venv/lib/python3.14/site-packages/sphinx/events.py", line 415, in emit
        raise ExtensionError(
        ...<4 lines>...
        ) from exc
    sphinx.errors.ExtensionError: Handler <function process_docstring at 0x7157711fb3d0> for event 'autodoc-process-docstring' threw an exception (exception: name 'PortfolioProtocol' is not defined)

This can be fixed by using annotationlib with format=annotationlib.Format.FORWARDREF instead of accessing __annotations__ directly, whenever annotationlib is available (Python 3.14+).

I implemented a workaround using monkey patches in pygaindalf's conf.py. With this, no exceptions are seen.

Note that sphinx.ext.autodoc has a related bug which also needs to be worked around for forward references to work: https://github.com/sphinx-doc/sphinx/issues/13945

ruipin avatar Oct 10 '25 14:10 ruipin

PR welcome 🤔

gaborbernat avatar Oct 13 '25 15:10 gaborbernat

Great, will send one once the upstream fix goes through!

ruipin avatar Oct 13 '25 16:10 ruipin