7

I have numpydoc-style docstrings:

def foobar(filename, copy, dtype, iterable, shape, files):
    """
    foobar is 42.

    Parameters
    ----------
    filename : str
    copy : bool
    dtype : data-type
    iterable : iterable object
    shape : int or tuple of int
    files : list of str

    Returns
    -------
    foobarfoo : int
    """
    pass

Is it possible to check if the docstring-types can possibly be correct?

(side question: Can numpy return/print the function signatures it discovered?)

For example, I would expect the following to fail:

Return Types

def foobar():
    """
    Returns
    -------
    blub : int
    """
    return "foo"

or

def foobar(a, b):
    """
    Parameters
    ----------
    a : number
    b : number

    Returns
    -------
    blub : int
    """
    if a > b:
        return "foo"
    return 42

Parameter types

def foobar(a, b):
    """
    Parameters
    ----------
    a : str
    b : int

    Returns
    -------
    blub : int
    """
    return a * b
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958

1 Answers1

3

No, mypy understands the official Python's typing notation only. See the mypy docs. And this fine, we don't need many alternative ways to type annotate, as

There should be one-- and preferably only one --obvious way to do it.

pawelswiecki
  • 562
  • 1
  • 4
  • 14
  • Aparently you got me wrong. I don't want mypy to assume the docstring is correct. I want to check the docstring correctnes with mypy. As to your comment about "only one way to do it": Can mypy generate documentation? – Martin Thoma Nov 09 '18 at 15:50
  • @MartinThoma I think I understood you correctly, after all, because my reply is the answer to "I want to check the docstring correctnes with mypy." problem as well :) So, mypy does not analyze docstrings at all, in any way. It uses Python's type annotations and the very code to get (or guess) types and analyze them. As far as I know, docstrings are *completely ignored* by mypy. – pawelswiecki Nov 09 '18 at 16:08
  • 1
    This is not exactly true. Mypy understands and parses docstrings as defined in PEP484. See the following link: https://mypy.readthedocs.io/en/latest/python2.html – Zoran Pavlovic Nov 12 '19 at 11:11
  • @ZoranPavlovic Could you quote the relevant parts of PEP 484 and docs you've linked to? I cannot find there anything about mypy understanding and parsing docstrings, but I may be missing something. – pawelswiecki Dec 06 '19 at 23:21
  • Heading. Type checking Python 2 code: For code that needs to be Python 2.7 compatible, function type annotations are given in comments, since the function annotation syntax was introduced in Python 3. – Zoran Pavlovic Dec 08 '19 at 18:11