Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Duplicated annotations in class and __init__() with autodoc typehints #461

Open
hanetar opened this issue Jul 6, 2024 · 0 comments
Open

Comments

@hanetar
Copy link

hanetar commented Jul 6, 2024

Hi. I found that when using autodoc typehints, the "Parameters" field from __init__() is duplicated in the class but without the descriptions. The return type is omitted in the class, but not in __init__(). For example,

class TestClass():
    """Class docstring"""

    def __init__(self, array: list[int]) -> None:
        """Constructor docstring

        :param array: Description of 'array'
        """

gives

autoapi_class_bad

Is this expected behavior?

I want just one set of annotations, either in the class or __init__(), depending on autoapi_python_class_content, i.e.:

"class"
autoapi_class_good

"init":
autoapi_init_good

"both":
autoapi_both

I was able to achieve this by (crudely) patching _record_typehints() in _mapper.py:

def _record_typehints(self, obj):
    if (
        isinstance(obj, (PythonClass, PythonFunction, PythonMethod))
        and not obj.overloads
    ) or isinstance(obj, PythonProperty):
        obj_annotations = {}

+        # remove "Return type" field from __init__() doc
-        include_return_annotation = True
+        include_return_annotation = not (isinstance(obj, PythonMethod) and obj.short_name == "__init__") 
        obj_data = obj.obj
        if isinstance(obj, PythonClass):
            constructor = obj.constructor
            if constructor:
+                # remove "Parameters" field from class doc if autoapi_python_class_content=="class"
+                if obj._class_content == "class":
+                    return
                include_return_annotation = False
                obj_data = constructor.obj
            else:
                return

        for _, name, annotation, _ in obj_data["args"]:
            if name and annotation:
                obj_annotations[name] = annotation

        return_annotation = obj_data["return_annotation"]
        if include_return_annotation and return_annotation:
            obj_annotations["return"] = return_annotation

        self.app.env.autoapi_annotations[obj.id] = obj_annotations

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant