Search code examples
pythontypesdocstring

Type hinting and having docs information


I have some method which takes two parameters, both of them are type hinted as "str". But I would also like to have some description attached to them. But most examples I found also want you to include the type in the docstring. Is there some neat way where I can keep the type hint outside of docstring but keep the description?

def extract_files(
        source_dir: str,
        working_dir: str,
) -> None:
    """
    Args:
        source_dir (str): some_important_description_1
        working_dir (str): some_import_description_2
    """

Solution

  • You can have anything you want in docsting. You don't have to follow a specific format if you don't want to. You can even still have automated docs if that's what you want to do later.

    For example, Sphinx will generate correct documentation as long docstring is correct RST. So, you can include or exclude whatever you want.

    See for more information: https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html

    For example, let's take this code:

    def extract_files(
            source_dir: str,
            working_dir: str,
    ) -> None:
        """
        Args:
          * ``source_dir``: some_important_description_1
          * ``working_dir``: some_import_description_2
        """
        pass
    

    Then create sample.rst with autofunction to generate docs.

    .. autofunction:: extract_files
    

    It will produce a document that looks like OK even without type hints in the docstring.

    enter image description here