TL;DR

raises is used to describe the possible exceptions being raised. raise is recognized by Sphinx when running autodoc and is the same as raises.

Full Explanation

PyCharm helps in using a few different styles of docstring comments.

Three which I often use are:

  1. NumPy Format
  2. Google Format
  3. Sphinx (much more than a format)

In all of these there is a special section for Raises which you can see in an older version of the PyCharm code tests:

  1. Simple NumPy
  2. Simple Google

The implementation for SphinxDocString we can see here there there are numerous keywords which can be recognized. Those tags then link to the list of RAISES_TAGS which can be found here.

I hope this information is useful.

Answer from erik-e on Stack Overflow
🌐
Python
peps.python.org › pep-0257
PEP 257 – Docstring Conventions | peps.python.org
The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object’s docstring.)
Discussions

python 3.x - Exception in docstring python3 - Stack Overflow
What is a best practice to insert Exception and Exception Type in docstring in python3? I use this pattern: def get_platform(cls, platform, channel): """ Get specific plafform in BotMachine More on stackoverflow.com
🌐 stackoverflow.com
Documenting exceptions that can happen in other functions in python docstrings - Stack Overflow
In Python, should we document in the docstrings exceptions that can be raised in other functions/classes besides the ones that are raised in the body of current function/method? Obs.: I'm consider... More on stackoverflow.com
🌐 stackoverflow.com
How to document error cases?
Haven't really looked at any code since you haven't taken the 'bots advice to format it properly. You can always use the function docstring to document exceptions that might be raised. The docstring becomes part of the function and can be found through introspection and the help() function . If the code is part of a large system and is user-facing you will have documentation somewhere where you can also list the exceptions raised by the function. More on reddit.com
🌐 r/learnpython
5
1
August 14, 2022
Custom exceptions defined in same python script cause "reference target not found" warnings
Describe the bug I have a python script which defines a custom exception class (that inherits from Exception). Within this same module I define a function that can raise this custom exception. I am using Google style docstrings, includin... More on github.com
🌐 github.com
1
March 20, 2023
🌐
Python
docs.python.org › 3 › c-api › exceptions.html
Exception Handling — Python 3.14.7 documentation
Same as PyErr_NewException(), except that the new exception class can easily be given a docstring: If doc is non-NULL, it will be used as the docstring for the exception class. Added in version 3.2.
🌐
Stack Overflow
stackoverflow.com › questions › 51994464 › documenting-exceptions-that-can-happen-in-other-functions-in-python-docstrings
Documenting exceptions that can happen in other functions in python docstrings - Stack Overflow
Either way is probably acceptable, but in that case is probably document whichever I chose, by adding something like “and any exceptions raised by the callback argument” to the end of the list. ... Does this answer your question? Should the docstring only contain the exceptions that are explicitly raised by a function?
🌐
Linux find Examples
queirozf.com › entries › python-docstrings-reference-examples
Python Docstrings: Reference & Examples
September 1, 2020 - Parameters ---------- arg1 : int Description of arg1 arg2 : str Description of arg2 Returns ------- bool Description of return value Raises ------ AttributeError The ``Raises`` section is a list of all exceptions that are relevant to the interface. ValueError If `arg2` is equal to `arg1`. See Also -------- otherfunc: some other related function Examples -------- These are written in doctest format, and should illustrate how to use the function. >>> a=1 >>> b=2 >>> func(a,b) True """ if arg1 == arg2: raise ValueError('arg1 must not be equal to arg2') return True · Doctests are a special form of docstring, used to inform users how to use a method but also to actually run tests.
🌐
Reddit
reddit.com › r/learnpython › how to document error cases?
r/learnpython on Reddit: How to document error cases?
August 14, 2022 -

Hello everyone, I'm new to Python, and it seems like there's no proper way of annotating which kinds of exceptions a function raises. Raising an error without making it part of the method signature might be fine for actually unexpected errors that should make the whole program terminate.

But what about kind of expected error? Like a file being unreadable or unable to parse. You can't just expect a programmer to know that code like this

def load_file(filename:string) -> MyFile:
    file = open(filename)
    
    return parse(file)

might throw an IOException, a ParseException, or a SpecialParseException. How should they know? Should they read all the source code from all the functions called, and all the sources codes from all the functions they called to know which exceptions they might have to handle?

So I tried returning errors instead. So instead, parse() is now going to return an error, and therefore, the signature needs to look like this:

def load_file(filename:string) -> Union[MyFile, ParseError, SpecialParseError, IOError]:
    try:   
        file = open(filename)
    except IOError as e:
        return e

    return parse(file)

I think that's much better, but on the Internet people say you should raise an exception wherever possible in Python. Also, this can get quite tedious, if you want to work with the result before returning, and just want to bubble errors up to the calling function:

def load_file(filename:string) -> Union[MyFile, ParseError, SpecialParseError, IOError]:
    try:   
        file = open(filename)
    except IOError as e:
        return e

    parsed = parse(file)

    if isinstance(parsed, Exception):
        return parsed

    specialtreatment(parsed)

    return parsed

Is there a better way to do this? I thought about, maybe an annotation, like this:

@raises ParseError, SpecialParseError, IOError
def load_file(filename:string) -> MyFile:
    file = open(filename)

    parsed = parse(file)

    specialtreatment(parsed)

    return parsed
🌐
GitHub
gist.github.com › nipunsadvilkar › a3c3b4a7a133b7780b4943e9adcfe83f
What is the standard Python docstring format? · GitHub
You can get some information about the main formats in that tuto. ... There follows the main used formats for docstrings. Historically a javadoc like style was prevalent, so it was taken as a base for Epydoc (with the called Epytext format) to generate documentation. ... @param param1: this is a first param @param param2: this is a second param @return: this is a description of what is returned @raise keyError: raises an exception """
Find elsewhere
🌐
Python
bugs.python.org › issue3715
Issue 3715: hashlib's docstring throws exception in pydoc - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/47965
🌐
Astral
docs.astral.sh › ruff › rules › docstring-missing-exception
docstring-missing-exception (DOC501) | Ruff - Astral Docs
This rule is unstable and in preview. The --preview flag is required for use. Checks for function docstrings that do not document all explicitly raised exceptions.
🌐
Lsst
developer.lsst.io › v › u-swinbank-typo-2018-04-12 › python › numpydoc.html
Documenting Python APIs with Docstrings — LSST DM Developer Guide u-swinbank-typo-2018-04-12 documentation
Don’t wrap each exception’s name with backticks, as we do when describing types in Parameters and Returns). No namespace prefix is needed when referring to exceptions in the same module as the API. Providing the full namespace is often a good idea, though. The description text is indented by four spaces from the docstring’s left justification.
🌐
O'Reilly
oreilly.com › library › view › python-in-a › 0596100469 › ch06s05.html
Custom Exception Classes - Python in a Nutshell, 2nd Edition [Book]
July 14, 2006 - As covered in The pass Statement, you don’t need a pass statement to make up the body of this class; the docstring (which you should always write) is quite sufficient to keep Python happy. Best style for such “empty” classes, just like for “empty” functions, is to have a docstring and no pass. Given the semantics of try/except, raising a custom exception class such as InvalidAttribute is almost the same as raising its standard exception superclass, AttributeError.
Author: Alex Martelli
Published: 2006
Pages: 734
🌐
DEV Community
dev.to › anatolyscherbakov › documented-make-docstrings-in-your-exceptions-work-2kcf
documented: make docstrings in your exceptions work - DEV Community
October 8, 2023 - I am now using it to format both internal and external exceptions for web and console applications. Flight condition nominal, so far. Perhaps this library will be useful for you too; you can easily grab it via ... Python software developer.
🌐
Noirlab
datalab.noirlab.edu › docs › manual › DevGuide › DocumentingPythonAPIswithDocstrings › DocumentingPythonAPIswithDocstrings.html
3.2. Documenting Python APIs with Docstrings — Data Lab documentation
Notes ----- Private members are any methods or attributes that start with an underscore and are *not* special. By default they are not included in the output. However, you should still provide docstrings for private members to document code for internal developers. """ pass class ExampleError(Exception): """Example exception.
🌐
Readthedocs
sphinxcontrib-napoleon.readthedocs.io › en › latest › example_google.html
Example Google Style Python Docstrings — napoleon 0.7 documentation
Attributes: msg (str): Human readable string describing the exception. code (int): Exception error code. """ def __init__(self, msg, code): self.msg = msg self.code = code class ExampleClass(object): """The summary line for a class docstring should fit on one line.
🌐
GitHub
github.com › sphinx-doc › sphinx › issues › 11256
Custom exceptions defined in same python script cause "reference target not found" warnings · Issue #11256 · sphinx-doc/sphinx
March 20, 2023 - If the custom exception is imported from another module then the "Raises:" section of the docstring documents without any warnings. Platform: darwin; (macOS-13.2.1-x86_64-i386-64bit) Python version: 3.11.0 (main, Nov 4 2022, 08:01:11) [Clang 13.1.6 (clang-1316.0.21.2.5)]) Python implementation: CPython Sphinx version: 6.1.3 Docutils version: 0.18.1 Jinja2 version: 3.1.2 Pygments version: 2.13.0
Author: sphinx-doc
🌐
Programiz
programiz.com › python-programming › docstrings
Python Docstrings (With Examples)
The docstring for a function or method should summarize its behavior and document its arguments and return values. It should also list all the exceptions that can be raised and other optional arguments. def add_binary(a, b): ''' Return the sum of two decimal numbers in binary digits.
Top answer
1 of 2
8

It depends what (or whom) you're writing the docstring for. For automatic conversion to API documentation, I like Google-style docstrings, which would look like:

def inv(a):
    """Return the inverse of the argument.

    Arguments:
      a (int): The number to invert.

    Returns:
      float: The inverse of the argument.

    Raises:
      TypeError: If 1 cannot be divided by the argument.
      ZeroDivisionError: If the argument is zero.

    """
    return 1 / a

Here I've included all of the exceptions that the function is likely to raise. Note that there's no need to explicitly raise ZeroDivisionError - that will happen automatically if you try to divide by zero.


However, if you aren't creating documentation from the docstring, I would probably just include the description line for such a simple function:

def inv(a):
    """Return the inverse of the argument."""
    return 1 / a 

Anyone using it is likely to know that you can't invert e.g. strings.


I don't want to check for types here, correct?

I wouldn't - if the user, after reading your documentation, decides to pass e.g. a string into the function they should expect to get the TypeError, and there's no point testing the argument type to then raise the same exception yourself that the code would have raised anyway (again, see also the ZeroDivisionError!) That is, unless e.g. float or complex numbers should be invalid input, in which case you will need to handle them manually.

2 of 2
0

No. The docstring should describe the input expected. If this were my function, I would include something like this in the docstring:

"""Return the inverse of an integer.  ZeroDivisionError is raised if zero is
passed to this function."""

Therefore it is specified that the input should be an integer. Specifying that the function can raise a TypeError just overly complicates the docstring.

🌐
Quora
clcoding.quora.com › How-to-list-Exception-along-with-docstring
How to list Exception along with docstring - Python Coding - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.