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
Press Ctrl+Alt+S and go to Editor | General |Smart Keys. Select the Insert type placeholders checkbox in the Smart Keys page of the editor settings. Place the caret at the function name, and press Alt+Enter . In the list of intention actions that opens, choose Insert documentation string stub.
Declaring Docstrings: The docstrings are declared using ”'triple single quotes”' or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.
Python will always remain a dynamically typed language. However, PEP 484 introduced type hints, which make it possible to also do static type checking of Python code. Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.
Press Ctrl+Q or choose View | Quick Documentation Lookup on the main menu. In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General | Code Completion. The Code completion page opens. Select the Show the documentation popup checkbox and specify the elapsed time.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With