Sphinx error: Recursion error: maximum recursion depth exceeded in comparison#

Did you Sphinx documentation project has failed with the error Recursion error: maximum recursion depth exceeded in comparison? This guide provides an explanation and solution to resolve the issue.

Symptom#

Sphinx build failed with error:

Recursion error: maximum recursion depth exceeded in comparison

This can happen with very large or deeply nested source files. You can
carefully increase the default Python recursion limit of 1000 in conf.py
with e.g.: import sys; sys.setrecursionlimit(1500)

Worry-free Sphinx?

Documatt app is a Sphinx-based tool which hides its complexity with free hosting for your books and docs.

Reason#

This rare issue usually occurs by human error. The common cause is creating circle reference between documents in a toctree:: directives.

Example#

For example toctree:: in index.rst include second.rst, and vise versa, second.rst includes index.rst. This creates circular reference that will quickly exhause Python recursion limit when Sphinx analyses documents.

index.rst#
First
=====

.. toctree::

   second
second.rst#
    Second
    ======

    .. toctree::

       index

Solution#

Fix circular reference in toctrees. In previous example, second.rst refer to index by error.