Skip to content

DOC502 (and by extension DOC503) should not be seen if called functions are already annotated with the given Exception #238

@AndreiMiculita

Description

@AndreiMiculita

DOC502: Function/method has a “Raises” section in the docstring, but there are not “raise” statements in the body
DOC503: Exceptions in the “Raises” section in the docstring do not match those in the function body

Suppose we have:

def foo(x):
    """
    Raises:
        ValueError: when bound check failed
    """
    checkAgainstBounds(x)
    manipulate(x)

def checkAgainstBounds(x):
    """
    Raises:
        ValueError: when X is not within bounds
    """
    if x < 0 or x > 100:
        raise ValueError(f"value {x} is out of bounds")
    maybeSomeOtherFunction()

This triggers DOC502.
But I propose this should be valid as the ValueError is explicitly declared in the docstring of checkAgainstBounds. It's not raised in foo, so to fix the DOC502 we need to explicitly re-raise it:

def foo(x):
    """
    Raises:
        ValueError: when bound check failed
    """
    try:
        checkAgainstBounds(x)
    except(e):
        raise ValueError(e.message) from e  # or something like that?
    manipulate(x)

To avoid having to do this, the behavior of DOC502 IMO should be changed so that exceptions can either be explicitly raised OR declared in the Raises of a function called in the given function.

It should be enough to only check one level down, i.e. not recurse further down the stack. Because we can assume checkAgainstBounds will itself be checked by the linter (so in this case if maybeSomeOtherFunction could raise an exception as well, it would be noticed when checking checkAgainstBounds).

In a large codebase, this would have a cascading effect, basically forcing developers to always either catch an exception in the function or declare it in the docstring. I've found code much easier to maintain and more secure that way when working on PHP (iirc it was this PHPStan rule: https://phpstan.org/blog/bring-your-exceptions-under-control#report-extra-exceptions-in-%40throws-that-aren%E2%80%99t-actually-thrown)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions