Skip to content

autodoc does not generate correct reStructuredText when type hints contain special characters #9266

@gousaiyang

Description

@gousaiyang

Describe the bug
If a type hint contains special characters (e.g. backslashes) which need to be escaped according to reStructuredText syntax, it is not correctly rendered.

To Reproduce
Steps to reproduce the behavior:

Code:

from typing import Literal


def func(arg: Literal['\\', '"', "'", '\n', '*', '``', ',.x']) -> Literal['\\', '"', "'", '\n', '*', '``', ',.x']:
    """My function.

    Args:
        arg: my arg

    Returns:
        my return value
    """
    return arg


#: This is a global variable.
global_var: Literal['\\', '"', "'", '\n', '*', '``', ',.x'] = '\n'


class Context:
    """My context class."""
    #: This is a class variable defined in class body.
    var1: Literal['\\', '"', "'", '\n', '*', '``', ',.x']

    def __init__(self) -> None:
        """Initialize context."""
        #: This is an attribute defined in __init__().
        self.var2: Literal['\\', '"', "'", '\n', '*', '``', ',.x'] = '\n'

Config:

extensions = [
    'sphinx.ext.napoleon',
    'sphinx.ext.autodoc',
]

autodoc_typehints = 'both'

napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = True
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = True
napoleon_use_admonition_for_notes = True
napoleon_use_admonition_for_references = True
napoleon_use_ivar = True
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_use_keyword = True
napoleon_custom_sections = None

Expected behavior
The type hint Literal['\\', '"', "'", '\n', '*', '``', ',.x'] should be correctly rendered in all places.

Screenshots
Actual render:
image

Specifically:

  • Quotes and \n are missing in many places
  • The backslash character is not properly displayed
  • In the function description part, the dot . after the comma , is missing

Environment info

Additional context
This is not a duplicate of #9195. #9196 has fixed the stringifying of Literal, but the generated reStructuredText could still be invalid as special characters are not properly escaped. Literal is just a reasonable example to insert arbitrary characters into type hints.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions