sphinx-doc / sphinx

The Sphinx documentation generator
https://www.sphinx-doc.org/
Other
6.61k stars 2.13k forks source link

Autodoc — wrong reftarget for Annotated class when documenting pydantic models #13091

Open federicodabrunzo opened 3 weeks ago

federicodabrunzo commented 3 weeks ago

Describe the bug

While I was trying to generate documentation with the autodoc extension I came into an issue for certain pydantic models. It looks like that under certain circumstances autodoc is interpreting the Annotated class to come from one of the project modules rather than the typing module.

To trigger the issue we need a project where:

.. docs/index.rst
.. autoclass:: example.models.CookingModel
#src/example/models.py

from typing import Annotated, Any
import pydantic
from . import enumerations

def validate(v: Any) -> Any:
    """
    This does nothing but triggers the error.
    """
    return v

class CookingModel(pydantic.BaseModel):
    fruit: Annotated[enumerations.FruitEnum, pydantic.BeforeValidator(validate)]
# src/example/enumerations.py

from enum import Enum

class FruitEnum(str, Enum):
    pear = "pear"
    banana = "banana"

With this project structure I'm using a custom extension to find the pending_xref nodes and what I find out is a node with a reftarget equals to example.enumerations.Annotated which is unexpected.

How to Reproduce

I have created a small test repo to illustrate and reproduce the issue.

Environment Information

Platform:              darwin; (macOS-14.6.1-arm64-arm-64bit)
Python version:        3.11.9 (main, Aug  5 2024, 10:14:41) [Clang 15.0.0 (clang-1500.3.9.4)])
Python implementation: CPython
Sphinx version:        8.1.3
Docutils version:      0.21.2
Jinja2 version:        3.1.4
Pygments version:      2.18.0

Sphinx extensions

extensions = [
    "some_reference_resolver", # This extension is just to print the reftarget of the nodes
    "sphinx.ext.autodoc",
]

Additional context

No response

electric-coder commented 3 weeks ago

Similar to #12601 that also had issues with typing.Annotated.