Home > Enterprise >  Defining docstring raises for functions not explicitly raising exception
Defining docstring raises for functions not explicitly raising exception

Time:02-16

import requests

def example():
  """
  An example function

  :raises KeyError: ?
  :raises HttpError: ?
  """
  result: Dict = do_something()
  log(result["key"])
  response = requests.get(url)
  return response

The above function is not explicitly raising any exception, but as can be seen, its execution can potentially raise KeyError and HTTPError. Is it fine to mention these in docstring? What does the best practice say?

CodePudding user response:

If the exceptions are relavant for somebody using the functions the should be documented (and also that they are indirect)

CodePudding user response:

This is too long for a comment, but it is not an answer either, because some parts of it contradict each other.

  1. Don't care about exceptions resulting from incorrect usage or problems with a computer that prevent normal program operation like disk full.

  2. If some exceptions can happen when the functions is used correctly (it should be documented what that means), they are part of the interface and should be documented.

  3. Networking is full of timeouts, outages, failed connections so that they may be consider normal.

  4. For example the requests.get itself does not mention exceptions it may raise (link: https://docs.python-requests.org/en/latest/_modules/requests/api/#get). It says you'll get a response. But what you can get if there is no valid response? An exception, nothing else. So it is "implied".

  • Related