Description¶
This package provides a light framework that can be used to automatically generate exceptions documentation marked up in reStructuredText.
The exdoc module details how to register exceptions, how to traced them and how to generate their documentation
Interpreter¶
The package has been developed and tested with Python 2.7, 3.5, 3.6 and 3.7 under Linux (Debian, Ubuntu), Apple macOS and Microsoft Windows
Installing¶
$ pip install pexdoc
Documentation¶
Available at Read the Docs
Contributing¶
Abide by the adopted code of conduct
Fork the repository from GitHub and then clone personal copy [1]:
$ github_user=myname $ git clone --recurse-submodules \ https://github.com/"${github_user}"/pexdoc.git Cloning into 'pexdoc'... ... $ cd pexdoc || exit 1 $ export PEXDOC_DIR=${PWD} $
The package uses two sub-modules: a set of custom Pylint plugins to help with some areas of code quality and consistency (under the
pylint_plugins
directory), and a lightweight package management framework (under thepypkg
directory). Additionally, the pre-commit framework is used to perform various pre-commit code quality and consistency checks. To enable the pre-commit hooks:$ cd "${PEXDOC_DIR}" || exit 1 $ pre-commit install pre-commit installed at .../pexdoc/.git/hooks/pre-commit $
Ensure that the Python interpreter can find the package modules (update the
$PYTHONPATH
environment variable, or use sys.paths(), etc.)$ export PYTHONPATH=${PYTHONPATH}:${PEXDOC_DIR} $
Install the dependencies (if needed, done automatically by pip):
- Cog (2.5.1 or newer)
- Coverage (4.5.3 or newer)
- Decorator (4.4.0 or newer)
- Docutils (0.14 or newer)
- Funcsigs (1.0.2 or newer)
- Inline Syntax Highlight Sphinx Extension (0.2 or newer)
- Mock (2.0.0 or newer)
- Pmisc (1.5.8 or newer)
- Ptrie (1.1.6 or newer)
- Py.test (4.3.1 or newer)
- PyContracts (1.8.2 or newer)
- Pydocstyle (3.0.0 or newer)
- Pylint (Python 2.x: 1.9.4 or newer, Python 3.x: 2.3.1 or newer)
- Pytest-coverage (2.6.1 or newer)
- Pytest-pmisc (1.0.7 or newer)
- Pytest-xdist (optional, 1.26.1 or newer)
- ReadTheDocs Sphinx theme (0.4.3 or newer)
- Shellcheck Linter Sphinx Extension (1.0.8 or newer)
- Sphinx (1.8.5 or newer)
- Tox (3.7.0 or newer)
- Virtualenv (16.4.3 or newer)
Implement a new feature or fix a bug
Write a unit test which shows that the contributed code works as expected. Run the package tests to ensure that the bug fix or new feature does not have adverse side effects. If possible achieve 100% code and branch coverage of the contribution. Thorough package validation can be done via Tox and Pytest:
$ PKG_NAME=pexdoc tox GLOB sdist-make: .../pexdoc/setup.py py27-pkg create: .../pexdoc/.tox/py27 py27-pkg installdeps: -r.../pexdoc/requirements/tests_py27.pip, -r.../pexdoc/requirements/docs_py27.pip ... py27-pkg: commands succeeded py35-pkg: commands succeeded py36-pkg: commands succeeded py37-pkg: commands succeeded congratulations :) $
Setuptools can also be used (Tox is configured as its virtual environment manager):
$ PKG_NAME=pexdoc python setup.py tests running tests running egg_info writing pexdoc.egg-info/PKG-INFO writing dependency_links to pexdoc.egg-info/dependency_links.txt writing requirements to pexdoc.egg-info/requires.txt ... py27-pkg: commands succeeded py35-pkg: commands succeeded py36-pkg: commands succeeded py37-pkg: commands succeeded congratulations :) $
Tox (or Setuptools via Tox) runs with the following default environments:
py27-pkg
,py35-pkg
,py36-pkg
andpy37-pkg
[3]. These use the 2.7, 3.5, 3.6 and 3.7 interpreters, respectively, to test all code in the documentation (both in Sphinx*.rst
source files and in docstrings), run all unit tests, measure test coverage and re-build the exceptions documentation. To pass arguments to Pytest (the test runner) use a double dash (--
) after all the Tox arguments, for example:$ PKG_NAME=pexdoc tox -e py27-pkg -- -n 4 GLOB sdist-make: .../pexdoc/setup.py py27-pkg inst-nodeps: .../pexdoc/.tox/.tmp/package/1/pexdoc-1.1.4.zip ... py27-pkg: commands succeeded congratulations :) $
Or use the
-a
Setuptools optional argument followed by a quoted string with the arguments for Pytest. For example:$ PKG_NAME=pexdoc python setup.py tests -a "-e py27-pkg -- -n 4" running tests ... py27-pkg: commands succeeded congratulations :) $
There are other convenience environments defined for Tox [3]:
py27-repl
,py35-repl
,py36-repl
andpy37-repl
run the Python 2.7, 3.5, 3.6 and 3.7 REPL, respectively, in the appropriate virtual environment. Thepexdoc
package is pip-installed by Tox when the environments are created. Arguments to the interpreter can be passed in the command line after a double dash (--
).py27-test
,py35-test
,py36-test
andpy37-test
run Pytest using the Python 2.7, 3.5, 3.6 and 3.7 interpreter, respectively, in the appropriate virtual environment. Arguments to pytest can be passed in the command line after a double dash (--
) , for example:$ PKG_NAME=pexdoc tox -e py27-test -- -x test_pexdoc.py GLOB sdist-make: .../pexdoc/setup.py py27-pkg inst-nodeps: .../pexdoc/.tox/.tmp/package/1/pexdoc-1.1.4.zip ... py27-pkg: commands succeeded congratulations :) $
py27-test
,py35-test
,py36-test
andpy37-test
test code and branch coverage using the 2.7, 3.5, 3.6 and 3.7 interpreter, respectively, in the appropriate virtual environment. Arguments to pytest can be passed in the command line after a double dash (--
). The report can be found in${PEXDOC_DIR}/.tox/py[PV]/usr/share/pe xdoc/tests/htmlcov/index.html
where[PV]
stands for2.7
,3.5
,3.6
or3.7
depending on the interpreter used.
Verify that continuous integration tests pass. The package has continuous integration configured for Linux, Apple macOS and Microsoft Windows (all via Azure DevOps).
Document the new feature or bug fix (if needed). The script
${PEXDOC_DIR}/pypkg/build_docs.py
re-builds the whole package documentation (re-generates images, cogs source files, etc.):$ "${PEXDOC_DIR}"/pypkg/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] Build pexdoc package documentation optional arguments: -h, --help show this help message and exit -d DIRECTORY, --directory DIRECTORY specify source file directory (default ../pexdoc) -r, --rebuild rebuild exceptions documentation. If no module name is given all modules with auto-generated exceptions documentation are rebuilt -n NUM_CPUS, --num-cpus NUM_CPUS number of CPUs to use (default: 1) -t, --test diff original and rebuilt file(s) (exit code 0 indicates file(s) are identical, exit code 1 indicates file(s) are different)
Footnotes
[1] | All examples are for the bash shell |
[2] | It is assumed that all the Python interpreters are in the executables path. Source code for the interpreters can be downloaded from Python’s main site |
[3] | (1, 2) Tox configuration largely inspired by Ionel’s codelog |
Changelog¶
- 1.1.4 [2019-03-21]: Dependency fix
- 1.1.3 [2019-03-21]: Dependency update
- 1.1.2 [2019-03-21]: Documentation and dependency update
- 1.1.1 [2019-03-04]: Updated package management framework
- 1.1.0 [2018-01-19]: Dropped support for Python interpreter versions 2.6, 3.3 and 3.4. Updated dependencies versions to their current versions
- 1.0.9 [2017-02-10]: Package build enhancements and fixes
- 1.0.8 [2017-02-07]: Python 3.6 support
- 1.0.7 [2017-01-02]: Suppressed deprecation warnings for Python 2.6
- 1.0.6 [2016-06-13]: Fixed Windows continuous integration failure
- 1.0.5 [2016-06-11]: Minor documentation build bug fix
- 1.0.4 [2016-05-13]: Documentation update
- 1.0.3 [2016-05-11]: Documentation update
- 1.0.2 [2016-05-11]: Documentation update
- 1.0.1 [2016-05-11]: Documentation update
- 1.0.0 [2016-05-01]: Final release of 1.0.0 branch
- 1.0.0rc1 [2016-05-01]: Initial commit, forked a subset from putil PyPI package
License¶
The MIT License (MIT)
Copyright (c) 2013-2019 Pablo Acosta-Serafini
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Contents¶
Description¶
This package provides a light framework that can be used to automatically generate exceptions documentation marked up in reStructuredText.
The exdoc module details how to register exceptions, how to traced them and how to generate their documentation
Interpreter¶
The package has been developed and tested with Python 2.7, 3.5, 3.6 and 3.7 under Linux (Debian, Ubuntu), Apple macOS and Microsoft Windows
Installing¶
$ pip install pexdoc
Documentation¶
Available at Read the Docs
Contributing¶
Abide by the adopted code of conduct
Fork the repository from GitHub and then clone personal copy [1]:
$ github_user=myname $ git clone --recurse-submodules \ https://github.com/"${github_user}"/pexdoc.git Cloning into 'pexdoc'... ... $ cd pexdoc || exit 1 $ export PEXDOC_DIR=${PWD} $
The package uses two sub-modules: a set of custom Pylint plugins to help with some areas of code quality and consistency (under the
pylint_plugins
directory), and a lightweight package management framework (under thepypkg
directory). Additionally, the pre-commit framework is used to perform various pre-commit code quality and consistency checks. To enable the pre-commit hooks:$ cd "${PEXDOC_DIR}" || exit 1 $ pre-commit install pre-commit installed at .../pexdoc/.git/hooks/pre-commit $
Ensure that the Python interpreter can find the package modules (update the
$PYTHONPATH
environment variable, or use sys.paths(), etc.)$ export PYTHONPATH=${PYTHONPATH}:${PEXDOC_DIR} $
Install the dependencies (if needed, done automatically by pip):
- Cog (2.5.1 or newer)
- Coverage (4.5.3 or newer)
- Decorator (4.4.0 or newer)
- Docutils (0.14 or newer)
- Funcsigs (1.0.2 or newer)
- Inline Syntax Highlight Sphinx Extension (0.2 or newer)
- Mock (2.0.0 or newer)
- Pmisc (1.5.8 or newer)
- Ptrie (1.1.6 or newer)
- Py.test (4.3.1 or newer)
- PyContracts (1.8.2 or newer)
- Pydocstyle (3.0.0 or newer)
- Pylint (Python 2.x: 1.9.4 or newer, Python 3.x: 2.3.1 or newer)
- Pytest-coverage (2.6.1 or newer)
- Pytest-pmisc (1.0.7 or newer)
- Pytest-xdist (optional, 1.26.1 or newer)
- ReadTheDocs Sphinx theme (0.4.3 or newer)
- Shellcheck Linter Sphinx Extension (1.0.8 or newer)
- Sphinx (1.8.5 or newer)
- Tox (3.7.0 or newer)
- Virtualenv (16.4.3 or newer)
Implement a new feature or fix a bug
Write a unit test which shows that the contributed code works as expected. Run the package tests to ensure that the bug fix or new feature does not have adverse side effects. If possible achieve 100% code and branch coverage of the contribution. Thorough package validation can be done via Tox and Pytest:
$ PKG_NAME=pexdoc tox GLOB sdist-make: .../pexdoc/setup.py py27-pkg create: .../pexdoc/.tox/py27 py27-pkg installdeps: -r.../pexdoc/requirements/tests_py27.pip, -r.../pexdoc/requirements/docs_py27.pip ... py27-pkg: commands succeeded py35-pkg: commands succeeded py36-pkg: commands succeeded py37-pkg: commands succeeded congratulations :) $
Setuptools can also be used (Tox is configured as its virtual environment manager):
$ PKG_NAME=pexdoc python setup.py tests running tests running egg_info writing pexdoc.egg-info/PKG-INFO writing dependency_links to pexdoc.egg-info/dependency_links.txt writing requirements to pexdoc.egg-info/requires.txt ... py27-pkg: commands succeeded py35-pkg: commands succeeded py36-pkg: commands succeeded py37-pkg: commands succeeded congratulations :) $
Tox (or Setuptools via Tox) runs with the following default environments:
py27-pkg
,py35-pkg
,py36-pkg
andpy37-pkg
[3]. These use the 2.7, 3.5, 3.6 and 3.7 interpreters, respectively, to test all code in the documentation (both in Sphinx*.rst
source files and in docstrings), run all unit tests, measure test coverage and re-build the exceptions documentation. To pass arguments to Pytest (the test runner) use a double dash (--
) after all the Tox arguments, for example:$ PKG_NAME=pexdoc tox -e py27-pkg -- -n 4 GLOB sdist-make: .../pexdoc/setup.py py27-pkg inst-nodeps: .../pexdoc/.tox/.tmp/package/1/pexdoc-1.1.4.zip ... py27-pkg: commands succeeded congratulations :) $
Or use the
-a
Setuptools optional argument followed by a quoted string with the arguments for Pytest. For example:$ PKG_NAME=pexdoc python setup.py tests -a "-e py27-pkg -- -n 4" running tests ... py27-pkg: commands succeeded congratulations :) $
There are other convenience environments defined for Tox [3]:
py27-repl
,py35-repl
,py36-repl
andpy37-repl
run the Python 2.7, 3.5, 3.6 and 3.7 REPL, respectively, in the appropriate virtual environment. Thepexdoc
package is pip-installed by Tox when the environments are created. Arguments to the interpreter can be passed in the command line after a double dash (--
).py27-test
,py35-test
,py36-test
andpy37-test
run Pytest using the Python 2.7, 3.5, 3.6 and 3.7 interpreter, respectively, in the appropriate virtual environment. Arguments to pytest can be passed in the command line after a double dash (--
) , for example:$ PKG_NAME=pexdoc tox -e py27-test -- -x test_pexdoc.py GLOB sdist-make: .../pexdoc/setup.py py27-pkg inst-nodeps: .../pexdoc/.tox/.tmp/package/1/pexdoc-1.1.4.zip ... py27-pkg: commands succeeded congratulations :) $
py27-test
,py35-test
,py36-test
andpy37-test
test code and branch coverage using the 2.7, 3.5, 3.6 and 3.7 interpreter, respectively, in the appropriate virtual environment. Arguments to pytest can be passed in the command line after a double dash (--
). The report can be found in${PEXDOC_DIR}/.tox/py[PV]/usr/share/pe xdoc/tests/htmlcov/index.html
where[PV]
stands for2.7
,3.5
,3.6
or3.7
depending on the interpreter used.
Verify that continuous integration tests pass. The package has continuous integration configured for Linux, Apple macOS and Microsoft Windows (all via Azure DevOps).
Document the new feature or bug fix (if needed). The script
${PEXDOC_DIR}/pypkg/build_docs.py
re-builds the whole package documentation (re-generates images, cogs source files, etc.):$ "${PEXDOC_DIR}"/pypkg/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] Build pexdoc package documentation optional arguments: -h, --help show this help message and exit -d DIRECTORY, --directory DIRECTORY specify source file directory (default ../pexdoc) -r, --rebuild rebuild exceptions documentation. If no module name is given all modules with auto-generated exceptions documentation are rebuilt -n NUM_CPUS, --num-cpus NUM_CPUS number of CPUs to use (default: 1) -t, --test diff original and rebuilt file(s) (exit code 0 indicates file(s) are identical, exit code 1 indicates file(s) are different)
Footnotes
[1] | All examples are for the bash shell |
[2] | It is assumed that all the Python interpreters are in the executables path. Source code for the interpreters can be downloaded from Python’s main site |
[3] | (1, 2) Tox configuration largely inspired by Ionel’s codelog |
Changelog¶
- 1.1.4 [2019-03-21]: Dependency fix
- 1.1.3 [2019-03-21]: Dependency update
- 1.1.2 [2019-03-21]: Documentation and dependency update
- 1.1.1 [2019-03-04]: Updated package management framework
- 1.1.0 [2018-01-19]: Dropped support for Python interpreter versions 2.6, 3.3 and 3.4. Updated dependencies versions to their current versions
- 1.0.9 [2017-02-10]: Package build enhancements and fixes
- 1.0.8 [2017-02-07]: Python 3.6 support
- 1.0.7 [2017-01-02]: Suppressed deprecation warnings for Python 2.6
- 1.0.6 [2016-06-13]: Fixed Windows continuous integration failure
- 1.0.5 [2016-06-11]: Minor documentation build bug fix
- 1.0.4 [2016-05-13]: Documentation update
- 1.0.3 [2016-05-11]: Documentation update
- 1.0.2 [2016-05-11]: Documentation update
- 1.0.1 [2016-05-11]: Documentation update
- 1.0.0 [2016-05-01]: Final release of 1.0.0 branch
- 1.0.0rc1 [2016-05-01]: Initial commit, forked a subset from putil PyPI package
License¶
The MIT License (MIT)
Copyright (c) 2013-2019 Pablo Acosta-Serafini
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
API¶
exdoc module¶
This module can be used to automatically generate exceptions documentation marked up in reStructuredText with help from cog and the pexdoc.exh module.
The exceptions to auto-document need to be defined with either the pexdoc.exh.ExHandle.addex() function, the pexdoc.exh.ExHandle.addai() function or via contracts of the pexdoc.pcontracts module, and “traced” before the documentation is generated. In general tracing consists of calling the methods, functions and/or class properties so that all the required exceptions are covered (exceptions raised by contracts are automatically traced when the functions with the contracts are used). A convenient way of tracing a module is to simply run its test suite, provided that it covers the exceptions that need to be documented (for maximum speed the unit tests that cover the exceptions may be segregated so that only these tests need to be executed).
For example, it is desired to auto-document the exceptions of a module
my_module.py
, which has tests in test_my_module.py
. Then a tracing
module trace_my_module.py
can be created to leverage the already written
tests:
# trace_my_module_1.py
# Option 1: use already written test bench
from __future__ import print_function
import copy, os, pytest, pexdoc
def trace_module(no_print=True):
"""Trace my_module exceptions."""
pwd = os.path.dirname(__file__)
script_name = os.path.join(pwd, "test_my_module.py")
with pexdoc.ExDocCxt() as exdoc_obj:
if pytest.main(["-s", "-vv", "-x", "{0}".format(script_name)]):
raise RuntimeError("Tracing did not complete successfully")
if not no_print:
module_prefix = "docs.support.my_module."
callable_names = ["func", "MyClass.value"]
for callable_name in callable_names:
callable_name = module_prefix + callable_name
print("\nCallable: {0}".format(callable_name))
print(exdoc_obj.get_sphinx_doc(callable_name, width=70))
print("\n")
return copy.copy(exdoc_obj)
if __name__ == "__main__":
trace_module(False)
The context manager pexdoc.exdoc.ExDocCxt sets up the tracing environment and returns a pexdoc.exdoc.ExDoc object that can the be used in the documentation string of each callable to extract the exceptions documentation. In this example it is assumed that the tests are written using pytest, but any test framework can be used. Another way to trace the module is to simply call all the functions, methods or class properties that need to be documented. For example:
# trace_my_module_2.py
# Option 2: manually use all callables to document
from __future__ import print_function
import copy, pexdoc, docs.support.my_module
def trace_module(no_print=True):
"""Trace my_module_original exceptions."""
with pexdoc.ExDocCxt() as exdoc_obj:
try:
docs.support.my_module.func("John")
obj = docs.support.my_module.MyClass()
obj.value = 5
obj.value
except:
raise RuntimeError("Tracing did not complete successfully")
if not no_print:
module_prefix = "docs.support.my_module."
callable_names = ["func", "MyClass.value"]
for callable_name in callable_names:
callable_name = module_prefix + callable_name
print("\nCallable: {0}".format(callable_name))
print(exdoc_obj.get_sphinx_doc(callable_name, width=70))
print("\n")
return copy.copy(exdoc_obj)
if __name__ == "__main__":
trace_module(False)
And the actual module my_module
code is (before auto-documentation):
"""
Test module.
[[[cog
import os, sys
sys.path.append(os.environ['TRACER_DIR'])
import trace_my_module_1
exobj = trace_my_module_1.trace_module(no_print=True)
]]]
[[[end]]]
"""
# my_module.py
import pexdoc
def func(name):
r"""
Print your name.
:param name: Name to print
:type name: string
.. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]]
.. [[[end]]]
"""
# Raise condition evaluated in same call as exception addition
pexdoc.addex(TypeError, "Argument `name` is not valid", not isinstance(name, str))
return "My name is {0}".format(name)
class MyClass(object):
"""Store a value."""
def __init__(self, value=None): # noqa
self._value = None if not value else value
def _get_value(self):
# Raise condition not evaluated in same call as
# exception additions
exobj = pexdoc.addex(RuntimeError, "Attribute `value` not set")
exobj(not self._value)
return self._value
def _set_value(self, value):
exobj = pexdoc.addex(RuntimeError, "Argument `value` is not valid")
exobj(not isinstance(value, int))
self._value = value
value = property(_get_value, _set_value)
r"""
Set or return a value
:type: integer
:rtype: integer or None
.. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]]
.. [[[end]]]
"""
A simple shell script can be written to automate the cogging of the
my_module.py
file:
#!/bin/bash
set -e
finish() {
export TRACER_DIR=""
cd ${cpwd}
}
trap finish EXIT
input_file=${1:-my_module.py}
output_file=${2:-my_module.py}
export TRACER_DIR=$(dirname ${input_file})
cog.py -e -x -o ${input_file}.tmp ${input_file} > /dev/null && \
mv -f ${input_file}.tmp ${input_file}
cog.py -e -o ${input_file}.tmp ${input_file} > /dev/null && \
mv -f ${input_file}.tmp ${output_file}
After the script is run and the auto-documentation generated, each callable has
a reStructuredText marked-up :raises:
section:
"""
Test module.
[[[cog
import os, sys
sys.path.append(os.environ['TRACER_DIR'])
import trace_my_module_1
exobj = trace_my_module_1.trace_module(no_print=True)
]]]
[[[end]]]
"""
# my_module_ref.py
import pexdoc
def func(name):
r"""
Print your name.
:param name: Name to print
:type name: string
.. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]]
.. Auto-generated exceptions documentation for
.. docs.support.my_module.func
:raises: TypeError (Argument \`name\` is not valid)
.. [[[end]]]
"""
# Raise condition evaluated in same call as exception addition
pexdoc.addex(TypeError, "Argument `name` is not valid", not isinstance(name, str))
return "My name is {0}".format(name)
class MyClass(object):
"""Store a value."""
def __init__(self, value=None): # noqa
self._value = None if not value else value
def _get_value(self):
# Raise condition not evaluated in same call as
# exception additions
exobj = pexdoc.addex(RuntimeError, "Attribute `value` not set")
exobj(not self._value)
return self._value
def _set_value(self, value):
exobj = pexdoc.addex(RuntimeError, "Argument `value` is not valid")
exobj(not isinstance(value, int))
self._value = value
value = property(_get_value, _set_value)
r"""
Set or return a value
:type: integer
:rtype: integer or None
.. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]]
.. Auto-generated exceptions documentation for
.. docs.support.my_module.MyClass.value
:raises:
* When assigned
* RuntimeError (Argument \`value\` is not valid)
* When retrieved
* RuntimeError (Attribute \`value\` not set)
.. [[[end]]]
"""
Warning
Due to the limited introspection capabilities of class properties, only properties defined using the property built-in function can be documented with pexdoc.exdoc.ExDoc.get_sphinx_autodoc(). Properties defined by other methods can still be auto-documented with pexdoc.exdoc.ExDoc.get_sphinx_doc() and explicitly providing the method/function name.
Context managers¶
-
class
pexdoc.exdoc.
ExDocCxt
(exclude=None, pickle_fname=None, in_callables_fname=None, out_callables_fname=None)¶ Bases: object
Context manager to simplify exception tracing.
This manager sets up the tracing environment and returns a pexdoc.ExDoc object that can the be used in the documentation string of each callable to extract the exceptions documentation with either pexdoc.ExDoc.get_sphinx_doc() or pexdoc.ExDoc.get_sphinx_autodoc().
Parameters: - exclude (list of strings or None) – Module exclusion list. A particular callable in an otherwise fully qualified name is omitted if it belongs to a module in this list. If None all callables are included
- pickle_fname (FileName or None) – File name to pickle traced exception handler (useful for debugging purposes). If None all pickle file is created
- in_callables_fname (FileNameExists or None) – File name that contains traced modules information. File can be produced by either the pexdoc.Callables.save() or pexdoc.exh.ExHandle.save_callables() methods
- out_callables_fname (FileNameExists or None) – File name to save traced modules information to in JSON format. If the file exists it is overwritten
Raises: - OSError (File [in_callables_fname] could not be found)
- RuntimeError (Argument `in_callables_fname` is not valid)
- RuntimeError (Argument `exclude` is not valid)
- RuntimeError (Argument `out_callables_fname` is not valid)
- RuntimeError (Argument `pickle_fname` is not valid)
For example:
# exdoc_example.py from pexdoc import contract @contract(number='int|float', frac_length='int,>=0', rjust=bool) def peng(number, frac_length, rjust=True): return str(number)
>>> from __future__ import print_function >>> import docs.support.exdoc_example >>> from pexdoc import ExDocCxt >>> with ExDocCxt() as exdoc_obj: ... value = docs.support.exdoc_example.peng(1e6, 3, False) >>> print(exdoc_obj.get_sphinx_doc('docs.support.exdoc_example.peng')) .. Auto-generated exceptions documentation for .. docs.support.exdoc_example.peng <BLANKLINE> :raises: * RuntimeError (Argument \`frac_length\` is not valid) <BLANKLINE> * RuntimeError (Argument \`number\` is not valid) <BLANKLINE> * RuntimeError (Argument \`rjust\` is not valid) <BLANKLINE> <BLANKLINE>
Classes¶
-
class
pexdoc.exdoc.
ExDoc
(exh_obj, depth=None, exclude=None)¶ Bases: object
Generate exception documentation with reStructuredText mark-up.
Parameters: - exh_obj (pexdoc.exh.ExHandle) – Exception handler containing exception information for the callable(s) to be documented
- depth (non-negative integer or None) – Default hierarchy levels to include in the exceptions per callable (see pexdoc.ExDoc.depth). If None exceptions at all depths are included
- exclude (list of strings or None) – Default list of (potentially partial) module and callable names to exclude from exceptions per callable (see pexdoc.ExDoc.exclude). If None all callables are included
Return type: pexdoc.ExDoc
Raises: - RuntimeError (Argument `depth` is not valid)
- RuntimeError (Argument `exclude` is not valid)
- RuntimeError (Argument `exh_obj` is not valid)
- RuntimeError (Exceptions database is empty)
- RuntimeError (Exceptions do not have a common callable)
- ValueError (Object of argument `exh_obj` does not have any exception trace information)
-
get_sphinx_autodoc
(depth=None, exclude=None, width=72, error=False, raised=False, no_comment=False)¶ Return exception list in reStructuredText auto-determining callable name.
Parameters: - depth (non-negative integer or None) – Hierarchy levels to include in the exceptions list (overrides default depth argument; see pexdoc.ExDoc.depth). If None exceptions at all depths are included
- exclude (list of strings or None) – List of (potentially partial) module and callable names to exclude from exceptions list (overrides default exclude argument, see pexdoc.ExDoc.exclude). If None all callables are included
- width (integer) – Maximum width of the lines of text (minimum 40)
- error (boolean) – Flag that indicates whether an exception should be raised if the callable is not found in the callables exceptions database (True) or not (False)
- raised (boolean) – Flag that indicates whether only exceptions that were raised (and presumably caught) should be documented (True) or all registered exceptions should be documented (False)
- no_comment (boolean) – Flag that indicates whether a reStructuredText comment labeling the callable (method, function or class property) should be printed (False) or not (True) before the exceptions documentation
Raises: - RuntimeError (Argument `depth` is not valid)
- RuntimeError (Argument `error` is not valid)
- RuntimeError (Argument `exclude` is not valid)
- RuntimeError (Argument `no_comment` is not valid)
- RuntimeError (Argument `raised` is not valid)
- RuntimeError (Argument `width` is not valid)
- RuntimeError (Callable not found in exception list: [name])
- RuntimeError (Unable to determine callable name)
-
get_sphinx_doc
(name, depth=None, exclude=None, width=72, error=False, raised=False, no_comment=False)¶ Return an exception list marked up in reStructuredText.
Parameters: - name (string) – Name of the callable (method, function or class property) to generate exceptions documentation for
- depth (non-negative integer or None) – Hierarchy levels to include in the exceptions list (overrides default depth argument; see pexdoc.ExDoc.depth). If None exceptions at all depths are included
- exclude (list of strings or None) – List of (potentially partial) module and callable names to exclude from exceptions list (overrides default exclude argument; see pexdoc.ExDoc.exclude). If None all callables are included
- width (integer) – Maximum width of the lines of text (minimum 40)
- error (boolean) – Flag that indicates whether an exception should be raised if the callable is not found in the callables exceptions database (True) or not (False)
- raised (boolean) – Flag that indicates whether only exceptions that were raised (and presumably caught) should be documented (True) or all registered exceptions should be documented (False)
- no_comment (boolean) – Flag that indicates whether a reStructuredText comment labeling the callable (method, function or class property) should be printed (False) or not (True) before the exceptions documentation
Raises: - RuntimeError (Argument `depth` is not valid)
- RuntimeError (Argument `error` is not valid)
- RuntimeError (Argument `exclude` is not valid)
- RuntimeError (Argument `no_comment` is not valid)
- RuntimeError (Argument `raised` is not valid)
- RuntimeError (Argument `width` is not valid)
- RuntimeError (Callable not found in exception list: [name])
-
depth
¶ Get or set the default hierarchy levels to include in the exceptions per callable.
For example, a function
my_func()
calls two other functions,get_data()
andprocess_data()
, and in turnget_data()
calls another function,open_socket()
. In this scenario, the calls hierarchy is:my_func <- depth = 0 ├get_data <- depth = 1 │└open_socket <- depth = 2 └process_data <- depth = 1
Setting
depth=0
means that only exceptions raised bymy_func()
are going to be included in the documentation; Settingdepth=1
means that only exceptions raised bymy_func()
,get_data()
andprocess_data()
are going to be included in the documentation; and finally settingdepth=2
(in this case it has the same effects asdepth=None
) means that only exceptions raised bymy_func()
,get_data()
,process_data()
andopen_socket()
are going to be included in the documentation.Return type: non-negative integer Raises: RuntimeError (Argument `depth` is not valid)
-
exclude
¶ Get or set default list of (potentially partial) module and callable names to exclude from exceptions per callable.
For example,
['firstmod.ex']
excludes all exceptions from modulesfirstmod.exh
andfirstmod.exdoc
(it acts asr'firstmod.ex*'
). In addition to these modules,['firstmod.ex', 'secmod.peng']
excludes exceptions from the functionsecmod.peng
.Return type: list Raises: RuntimeError (Argument `exclude` is not valid)
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
'