exh module¶
This module can be used to register exceptions and then raise them if a given condition is true. For example:
# exh_example.py
from __future__ import print_function
from pexdoc.exh import addex
def my_func(name):
"""Sample function."""
# Add exception
exobj = addex(TypeError, "Argument `name` is not valid")
# Conditionally raise exception
exobj(not isinstance(name, str))
print("My name is {0}".format(name))
>>> import docs.support.exh_example
>>> docs.support.exh_example.my_func('Tom')
My name is Tom
>>> docs.support.exh_example.my_func(5)
Traceback (most recent call last):
...
TypeError: Argument `name` is not valid
When my_func()
gets called with anything but a string as an argument
a TypeError
exception is raised with the message
'Argument `name ` is not valid'
. While adding an exception with
pexdoc.exh.addex() and conditionally raising it takes the same number
of lines of code as an exception raised inside an if
block (or less
since the raise condition can be evaluated in the same
pexdoc.exh.addex() call) and incurs a slight performance penalty, using
the pexdoc.exh module allows for automatic documentation of the
exceptions raised by any function, method or class property with the help of
the pexdoc.exdoc module.
Functions¶
-
pexdoc.exh.
addex
(extype, exmsg, condition=None, edata=None)¶ Add an exception in the global exception handler.
Parameters: - extype (Exception type object, i.e. RuntimeError, TypeError, etc.) – Exception type; must be derived from the Exception class
- exmsg (string) – Exception message; it can contain fields to be replaced
when the exception is raised via
pexdoc.ExHandle.raise_exception_if().
A field starts with the characters
'