Skip to content

autodoc doesn't handle TypeVars or document user-defined generic classes accurately #8219

@anselor

Description

@anselor

Describe the bug

  1. TypeVar aliases aren't resolved
    When using automodule, if a TypeVar is used, the TypeVar isn't being recognized. With nitpick on, this warning is generated:
    helloworld.py:docstring of helloworld.helloworld.MyGenericType.foo:: WARNING: py:class reference target not found: MyTypeVar
    I can add it to the nitpick ignore list, but then all of the parameters that reference it aren't recognized and linked.

  2. typing.Generic type parameters for user-defined generic classes aren't documented

  3. Constructor for user-defined generic classes are always (*args, **kwargs) instead of what's actually declared.

To Reproduce

Simple doc file index.rst:

Hello World
===========

code docs
=========

.. automodule:: helloworld.helloworld
    :members:
    :undoc-members:
    :show-inheritance:

Here's an example module helloworld.py:

from typing import Generic, TypeVar

MyTypeVar = TypeVar('MyTypeVar')

class MyGenericType(Generic[MyTypeVar]):
    def __init__(self, param: MyTypeVar) -> None:
        pass

    def foo(self, param: MyTypeVar) -> None:
        pass

Expected behavior
Ideally:

  1. I would expect TypeVar definitions to be recognized as types
  2. Generic classes should document the TypeVars passed to typing.Generic
  3. Constructor for generic classes should reflect the parameters declared in the constructor.

Work-around for Item 1

This is less than ideal, but I can get the TypeVar to resolve by manually documenting it as an attribute like this:

.. py:attribute:: MyTypeVar
   :type: TypeVar
   :value: TypeVar('MyTypeVar')

This is the type used in MyGenericClass

.. automodule:: helloworld.helloworld
    :members:
    :undoc-members:
    :show-inheritance:

Your project
I've included a simple example above

Screenshots
Here's the generated documentation:
image

Here's the generated output with the manual attribute work-around:
image

Environment info

  • OS: Ubuntu 18.04, Ubuntu 20.04
  • Python version: 3.6.9, 3.8.2
  • Sphinx version: 3.1.2, 3.2.1
  • Sphinx extensions: sphinx.ext.autodoc
  • Extra tools: Viewing output on Chrome

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions