Hanif
Hanif

Reputation: 140

How to make PyCharm get type hints from function definition and populate type values in docstrings?

I always use type hints in function definitions, for example:

def foo(a: int, b: str) -> bool:
    pass

When I use PyCharm auto docstring generator to make docstrings in my code, I get this:

def foo(a: int, b: str) -> bool:
    """
    :param a: 
    :type a: 
    :param b: 
    :type b: 
    """
    pass

As you can see, the type values which I defined in the function itself have not been recognized by PyCharm, and I should write them in docstring again. How I can make PyCharm to auto-generate something like this for me (read type values from first line and insert them in the docstring):

def foo(a: int, b: str) -> bool:
    """
    :param a:
    :type a: int
    :param b:
    :type b: str
    :rtype: bool
    """
    pass

Upvotes: 14

Views: 5971

Answers (2)

Arigion
Arigion

Reputation: 3548

There is a feature request on the PyCharm Bugtracker: Generate docstring types based on the existed inline annotations

As of end of 2020 it seems that PyCharm still does not support adding the type information from the method to the docstring automagically.

There is a comment on the feature request asking why one would need such a functionality:

A question to everyone following, why do you need to put type hints both in annotations and docstrings? The latter format is only partially supported by PyCharm (not every possible PEP 484 type hint is understood there, see PY-23400) and not recognized at all by most other type checkers. Type hints in annotations, on the other hand, are already properly displayed in Quick Documentation and in the documentation rendered by Sphinx (perhaps with the help of sphinx-autodoc-typehints).

Upvotes: 7

Eskapp
Eskapp

Reputation: 3635

Go to Settings -> Editor -> Intentions. There, under the category Python, tick in the box Specify type for reference in docstring.

Once this is activated you can use the debugger and its functionality: Insert documentation string stub to populate the docstring of the function. (Note that you will need to activate the option Collect runtime information for code insight located Settings -> Build, Execution, Deployment -> Python Debugger)

The process is a bit long to detail so, I will give the link of the official PyCharm tutorial about this: https://www.jetbrains.com/help/pycharm/using-docstrings-to-specify-types.html

Upvotes: -2

Related Questions