Search code examples
pythonpycharmtypingdocstring

Using typing module in docstring


Suppose I have a function with a docstring where I declare the return type as a tuple with two strings:

def foo():
    """
    Returns:
        Tuple[str, str]: Tuple of first name and last name
    """

Am I supposed to import Tuple from typing if I don't use it anywhere except for in docstrings?


Solution

  • PyCharm's docstring support for type hints does not actually use typing. You do not need to import the module.

    The typing module is only there to support the fact that annotations are executed at runtime; for a statement starting with def foo() -> Tuple[str, str]:, Python will actually evaluate the expression Tuple[str, str] so expects to be able to resolve the names. (As of Python 3.7 you can disable (or rather, postpone) the evaluation with from __future__ import annotations).

    But a docstring is not evaluated, normally, and is not expected to be able to contain runnable Python code.

    Unless you have a hard requirement to put the type info in the docstring, I'd stick with actual annotations:

    from typing import Tuple
    
    
    # type aliases
    firstname = str
    lastname = str
    
    
    def foo() -> Tuple[firstname, lastname]:
        """Descriptive line documenting this function's purpose"""
        # ...