Using custom typehints with Sphinx and Pydantic

320 Views Asked by At

My Python project defines classes which inherit BaseModel from Pydantic. I then run Sphinx on the project, using apidoc with autodoc-pydantic.

The problem is that Sphinx does not generate docs when a class variable has a type hint of another class, where the second class does not inherit BaseModel.

Minimal Working Example

from pydantic import BaseModel

class MyClassOne(BaseModel):
    r"""
    To use as a test for a type hint. Inherits BaseModel.
    """


class MyClassTwo:
    r"""
    Another class to use as a type hint. Does not inherit BaseModel.
    """


class MyClassThree(BaseModel):
    r"""
    Use the other classes as types.
    """

    var_1: MyClassOne = None  #: Uses typehint which inherits BaseModel
    # var_2: MyClassTwo = None  #: Uses typehint which does not inherit BaseModel

with conf.py:

import os
import sys

sys.path.insert(0, os.path.abspath(".."))
sys.setrecursionlimit(1500)

project = "Demo Sphinx/Pydantic bug"
copyright = "2023,"
author = "N/A"
release = "1.0.0"

extensions = [
    "sphinx.ext.autodoc",
    "sphinxcontrib.apidoc",
    "sphinxcontrib.autodoc_pydantic",
]

templates_path = ["_templates"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
html_theme = "sphinx_rtd_theme"
autodoc_pydantic_model_show_json = False

It seems to work okay to use MyClassOne, since it inherits BaseModel, but if I uncomment var_2, the documentation fails. Is there a workaround to allow using any class as the typehint?

Thanks.

1

There are 1 best solutions below

0
Brian On

If anyone has the above issue, it can be solved by including a Config class in your class:

from pydantic import BaseModel

class MyClassOne(BaseModel):
    pass 

class MyClassTwo:
    pass 

class MyClassThree(BaseModel):
    r"""
    Use the other classes as types.
    """

    var_1: MyClassOne = None  #: Uses typehint which inherits BaseModel
    var_2: MyClassTwo = None  #: Uses typehint which does not inherit BaseModel

    class Config:
        arbitrary_types_allowed = True

However, this does not work in the case the object used as a type hint is imported from a mock package. For this case I have submitted an issue on github.