Putil Library¶
This library provides a collection of utility modules to supplement the Python standard library. The modules provided are:
- eng: engineering-related functions including a) handling numbers represented in engineering notation, obtaining their constituent components and converting to and from regular floats; b) pretty printing Numpy vectors; and c) formatting numbers represented in scientific notation with a greater degree of control and options than standard Python string formatting
- exdoc: automatically generate exceptions documentation marked up in reStructuredText with help from Cog and the exh module
- exh: register exceptions and then raise them if a given condition is true
- misc: miscellaneous utility functions that can be applied in a variety of circumstances; there are context managers, membership functions (test if an argument is of a given type), numerical functions and string functions
- pcontracts: thin wrapper around the PyContracts library that enables customization of the exception type raised and limited customization of the exception message
- pcsv: handle comma-separated values (CSV) files and do lightweight processing of their data
- pinspect: supplement Python’s introspection capabilities
- plot: create high-quality, presentation-ready X-Y graphs quickly and easily
- ptypes: several pseudo-type definitions which can be enforced and/or validated with custom contracts defined using the pcontracts module
- test: functions to aid in the unit testing of modules in the package (Py.test-based)
- tree: build, handle, process and search tries
Interpreter¶
The package has been developed and tested with Python 2.6, 2.7, 3.3, 3.4 and 3.5 under Linux (Debian, Ubuntu) and Microsoft Windows
Installing¶
$ pip install putil
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]:
$ git clone \ https://github.com/[github-user-name]/putil.git Cloning into 'putil'... ... $ cd putil $ export PUTIL_DIR=${PWD}
Install the project’s Git hooks and build the documentation. The pre-commit hook does some minor consistency checks, namely trailing whitespace and PEP8 compliance via Pylint. Assuming the directory to which the repository was cloned is in the
$PUTIL_DIR
shell environment variable:$ ${PUTIL_DIR}/sbin/complete-cloning.sh Installing Git hooks Building putil package documentation ...
Ensure that the Python interpreter can find the package modules (update the
$PYTHONPATH
environment variable, or use sys.paths(), etc.)$ export PYTHONPATH=${PYTHONPATH}:${PUTIL_DIR}
Install the dependencies (if needed, done automatically by pip):
- Astroid (older than 1.4)
- Cog (2.4 or newer)
- Coverage (3.7.1 or newer)
- Decorator (3.4.2 or newer)
- Funcsigs (Python 2.x only, 0.4 or newer)
- Inline Syntax Highlight Sphinx Extension (0.2 or newer)
- Matplotlib (1.3.1 or newer)
- Mock (Python 2.x only, 1.0.1 or newer)
- Numpy (1.8.2 or newer)
- Pillow (2.6.1 or newer)
- Py.test (2.7.0 or newer)
- PyContracts (1.7.2 or newer except 1.7.7)
- Pylint (Python 2.6: 1.3 or newer and older than 1.4, Python 2.7 or newer: 1.3.1 or newer and older than 1.5)
- Pytest-coverage (1.8.0 or newer)
- Pytest-xdist (optional, 1.8.0 or newer)
- ReadTheDocs Sphinx theme (0.1.9 or newer)
- Scipy (0.13.3 or newer)
- Six (1.4.0 or newer)
- Sphinx (1.2.3 or newer)
- Tox (1.9.0 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 setuptools:
$ python setup.py tests running tests running egg_info writing requirements to putil.egg-info/requires.txt writing putil.egg-info/PKG-INFO ...
Setuptools runs tox with its default environments:
py26-pkg
,py27-pkg
,py33-pkg
,py34-pkg
andpy35-pkg
[2]. These use the Python 2.6, 2.7, 3.3, 3.4 and 3.5 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 tox use the-a
setuptools option followed by a quoted string. For example:$ python setup.py tests -a "-e py27-pkg -- -n 4" running tests ...
There are other convenience environments defined for tox [3]:
py26-repl
,py27-repl
,py33-repl
,py34-repl
andpy35-repl
run the Python 2.6, 2.7, 3.3, 3.4 or 3.5 REPL, respectively, in the appropriate virtual environment. Theputil
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 (--
)py26-test
,py27-test
,py33-test
,py34-test
andpy35-test
run py.test using the Python 2.6, 2.7, 3.3, 3.4 or Python 3.5 interpreter, respectively, in the appropriate virtual environment. Arguments to py.test can be passed in the command line after a double dash (--
) , for example:$ tox -e py34-test -- -x test_eng.py GLOB sdist-make: [...]/putil/setup.py py34-test inst-nodeps: [...]/putil/.tox/dist/putil-[...].zip py34-test runtests: PYTHONHASHSEED='680528711' py34-test runtests: commands[0] | [...]py.test -x test_eng.py ==================== test session starts ==================== platform linux -- Python 3.4.2 -- py-1.4.30 -- [...] ...
py26-cov
,py27-cov
,py33-cov
,py34-cov
andpy35-cov
test code and branch coverage using the Python 2.6, 2.7, 3.3, 3.4 or 3.5 interpreter, respectively, in the appropriate virtual environment. Arguments to py.test can be passed in the command line after a double dash (--
). The report can be found in${PUTIL_DIR}/.tox/py[PV]/usr/share/putil/tests/htmlcov/index.html
where[PV]
stands for26
,27
,33
,34
or35
depending on the interpreter used
Verify that continuous integration tests pass. The package has continuous integration configured for Linux (via Travis) and for Microsoft Windows (via Appveyor). Aggregation/cloud code coverage is configured via Codecov
Document the new feature or bug fix (if needed). The script
${PUTIL_DIR}/sbin/build_docs.py
re-builds the whole package documentation (re-generates images, cogs source files, etc.):$ ${PUTIL_DIR}/sbin/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] [module_name [module_name ...]] Build putil package documentation positional arguments: module_name Module name for which to build documentation for optional arguments: -h, --help show this help message and exit -d DIRECTORY, --directory DIRECTORY specify source file directory (default ../putil) -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)
Output of shell commands can be automatically included in reStructuredText source files with the help of Cog and the
docs.support.term_echo
module.-
docs.support.term_echo.
ste
(command, nindent, mdir, fpointer) Simplified terminal echo; prints stdout resulting from a given Bash shell command (relative to the package
sbin
directory) formatted in reStructuredTextParameters: - command (string) – Bash shell command, relative to
${{PUTIL_DIR}}/sbin
- nindent (integer) – Indentation level
- mdir (string) – Module directory
- fpointer (function pointer) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging, for example
For example:
.. This is a reStructuredText file snippet .. [[[cog .. import os, sys .. from docs.support.term_echo import term_echo .. file_name = sys.modules['docs.support.term_echo'].__file__ .. mdir = os.path.realpath( .. os.path.dirname( .. os.path.dirname(os.path.dirname(file_name)) .. ) .. ) .. [[[cog ste('build_docs.py -h', 0, mdir, cog.out) ]]] .. code-block:: bash $ ${PUTIL_DIR}/sbin/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] [module_name [module_name ...]] ... .. ]]]
- command (string) – Bash shell command, relative to
-
docs.support.term_echo.
term_echo
(command, nindent=0, env=None, fpointer=None, cols=60) Terminal echo; prints stdout resulting from a given Bash shell command formatted in reStructuredText
Parameters: - command (string) – Bash shell command
- nindent (integer) – Indentation level
- env (dictionary) – Environment variable replacement dictionary. The Bash
command is pre-processed and any environment variable
represented in the full notation (
${...}
) is replaced. The dictionary key is the environment variable name and the dictionary value is the replacement value. For example, if command is'${PYTHON_CMD} -m "x=5"'
and env is{'PYTHON_CMD':'python3'}
the actual command issued is'python3 -m "x=5"'
- fpointer (function pointer) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging, for example - cols (integer) – Number of columns of output
Similarly Python files can be included in docstrings with the help of Cog and the
docs.support.incfile
module-
docs.support.incfile.
incfile
(fname, fpointer, lrange='1, 6-') Includes a Python source file in a docstring formatted in reStructuredText
Parameters: - fname (string) – File name, relative to environment variable
${TRACER_DIR}
- fpointer (function pointer) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging, for example - lrange (string) – Line range to include, similar to Sphinx literalinclude directive
For example:
def func(): """ This is a docstring. This file shows how to use it: .. =[=cog .. import docs.support.incfile .. docs.support.incfile.incfile('func_example.py', cog.out) .. =]= .. code-block:: python # func_example.py if __name__ == '__main__': func() .. =[=end=]= """ return 'This is func output'
- fname (string) – File name, relative to environment variable
-
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] | Tox configuration largely inspired by Ionel’s codelog |
Changelog¶
- 0.9.1rc1 [2015-11-30]: Initial public release
License¶
The MIT License (MIT)
Copyright (c) 2013-2015 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¶
Putil Library¶
This library provides a collection of utility modules to supplement the Python standard library. The modules provided are:
- eng: engineering-related functions including a) handling numbers represented in engineering notation, obtaining their constituent components and converting to and from regular floats; b) pretty printing Numpy vectors; and c) formatting numbers represented in scientific notation with a greater degree of control and options than standard Python string formatting
- exdoc: automatically generate exceptions documentation marked up in reStructuredText with help from Cog and the exh module
- exh: register exceptions and then raise them if a given condition is true
- misc: miscellaneous utility functions that can be applied in a variety of circumstances; there are context managers, membership functions (test if an argument is of a given type), numerical functions and string functions
- pcontracts: thin wrapper around the PyContracts library that enables customization of the exception type raised and limited customization of the exception message
- pcsv: handle comma-separated values (CSV) files and do lightweight processing of their data
- pinspect: supplement Python’s introspection capabilities
- plot: create high-quality, presentation-ready X-Y graphs quickly and easily
- ptypes: several pseudo-type definitions which can be enforced and/or validated with custom contracts defined using the pcontracts module
- test: functions to aid in the unit testing of modules in the package (Py.test-based)
- tree: build, handle, process and search tries
Interpreter¶
The package has been developed and tested with Python 2.6, 2.7, 3.3, 3.4 and 3.5 under Linux (Debian, Ubuntu) and Microsoft Windows
Installing¶
$ pip install putil
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]:
$ git clone \ https://github.com/[github-user-name]/putil.git Cloning into 'putil'... ... $ cd putil $ export PUTIL_DIR=${PWD}
Install the project’s Git hooks and build the documentation. The pre-commit hook does some minor consistency checks, namely trailing whitespace and PEP8 compliance via Pylint. Assuming the directory to which the repository was cloned is in the
$PUTIL_DIR
shell environment variable:$ ${PUTIL_DIR}/sbin/complete-cloning.sh Installing Git hooks Building putil package documentation ...
Ensure that the Python interpreter can find the package modules (update the
$PYTHONPATH
environment variable, or use sys.paths(), etc.)$ export PYTHONPATH=${PYTHONPATH}:${PUTIL_DIR}
Install the dependencies (if needed, done automatically by pip):
- Astroid (older than 1.4)
- Cog (2.4 or newer)
- Coverage (3.7.1 or newer)
- Decorator (3.4.2 or newer)
- Funcsigs (Python 2.x only, 0.4 or newer)
- Inline Syntax Highlight Sphinx Extension (0.2 or newer)
- Matplotlib (1.3.1 or newer)
- Mock (Python 2.x only, 1.0.1 or newer)
- Numpy (1.8.2 or newer)
- Pillow (2.6.1 or newer)
- Py.test (2.7.0 or newer)
- PyContracts (1.7.2 or newer except 1.7.7)
- Pylint (Python 2.6: 1.3 or newer and older than 1.4, Python 2.7 or newer: 1.3.1 or newer and older than 1.5)
- Pytest-coverage (1.8.0 or newer)
- Pytest-xdist (optional, 1.8.0 or newer)
- ReadTheDocs Sphinx theme (0.1.9 or newer)
- Scipy (0.13.3 or newer)
- Six (1.4.0 or newer)
- Sphinx (1.2.3 or newer)
- Tox (1.9.0 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 setuptools:
$ python setup.py tests running tests running egg_info writing requirements to putil.egg-info/requires.txt writing putil.egg-info/PKG-INFO ...
Setuptools runs tox with its default environments:
py26-pkg
,py27-pkg
,py33-pkg
,py34-pkg
andpy35-pkg
[2]. These use the Python 2.6, 2.7, 3.3, 3.4 and 3.5 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 tox use the-a
setuptools option followed by a quoted string. For example:$ python setup.py tests -a "-e py27-pkg -- -n 4" running tests ...
There are other convenience environments defined for tox [3]:
py26-repl
,py27-repl
,py33-repl
,py34-repl
andpy35-repl
run the Python 2.6, 2.7, 3.3, 3.4 or 3.5 REPL, respectively, in the appropriate virtual environment. Theputil
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 (--
)py26-test
,py27-test
,py33-test
,py34-test
andpy35-test
run py.test using the Python 2.6, 2.7, 3.3, 3.4 or Python 3.5 interpreter, respectively, in the appropriate virtual environment. Arguments to py.test can be passed in the command line after a double dash (--
) , for example:$ tox -e py34-test -- -x test_eng.py GLOB sdist-make: [...]/putil/setup.py py34-test inst-nodeps: [...]/putil/.tox/dist/putil-[...].zip py34-test runtests: PYTHONHASHSEED='680528711' py34-test runtests: commands[0] | [...]py.test -x test_eng.py ==================== test session starts ==================== platform linux -- Python 3.4.2 -- py-1.4.30 -- [...] ...
py26-cov
,py27-cov
,py33-cov
,py34-cov
andpy35-cov
test code and branch coverage using the Python 2.6, 2.7, 3.3, 3.4 or 3.5 interpreter, respectively, in the appropriate virtual environment. Arguments to py.test can be passed in the command line after a double dash (--
). The report can be found in${PUTIL_DIR}/.tox/py[PV]/usr/share/putil/tests/htmlcov/index.html
where[PV]
stands for26
,27
,33
,34
or35
depending on the interpreter used
Verify that continuous integration tests pass. The package has continuous integration configured for Linux (via Travis) and for Microsoft Windows (via Appveyor). Aggregation/cloud code coverage is configured via Codecov
Document the new feature or bug fix (if needed). The script
${PUTIL_DIR}/sbin/build_docs.py
re-builds the whole package documentation (re-generates images, cogs source files, etc.):$ ${PUTIL_DIR}/sbin/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] [module_name [module_name ...]] Build putil package documentation positional arguments: module_name Module name for which to build documentation for optional arguments: -h, --help show this help message and exit -d DIRECTORY, --directory DIRECTORY specify source file directory (default ../putil) -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)
Output of shell commands can be automatically included in reStructuredText source files with the help of Cog and the
docs.support.term_echo
module.-
docs.support.term_echo.
ste
(command, nindent, mdir, fpointer) Simplified terminal echo; prints stdout resulting from a given Bash shell command (relative to the package
sbin
directory) formatted in reStructuredTextParameters: - command (string) – Bash shell command, relative to
${{PUTIL_DIR}}/sbin
- nindent (integer) – Indentation level
- mdir (string) – Module directory
- fpointer (function pointer) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging, for example
For example:
.. This is a reStructuredText file snippet .. [[[cog .. import os, sys .. from docs.support.term_echo import term_echo .. file_name = sys.modules['docs.support.term_echo'].__file__ .. mdir = os.path.realpath( .. os.path.dirname( .. os.path.dirname(os.path.dirname(file_name)) .. ) .. ) .. [[[cog ste('build_docs.py -h', 0, mdir, cog.out) ]]] .. code-block:: bash $ ${PUTIL_DIR}/sbin/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] [module_name [module_name ...]] ... .. ]]]
- command (string) – Bash shell command, relative to
-
docs.support.term_echo.
term_echo
(command, nindent=0, env=None, fpointer=None, cols=60) Terminal echo; prints stdout resulting from a given Bash shell command formatted in reStructuredText
Parameters: - command (string) – Bash shell command
- nindent (integer) – Indentation level
- env (dictionary) – Environment variable replacement dictionary. The Bash
command is pre-processed and any environment variable
represented in the full notation (
${...}
) is replaced. The dictionary key is the environment variable name and the dictionary value is the replacement value. For example, if command is'${PYTHON_CMD} -m "x=5"'
and env is{'PYTHON_CMD':'python3'}
the actual command issued is'python3 -m "x=5"'
- fpointer (function pointer) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging, for example - cols (integer) – Number of columns of output
Similarly Python files can be included in docstrings with the help of Cog and the
docs.support.incfile
module-
docs.support.incfile.
incfile
(fname, fpointer, lrange='1, 6-') Includes a Python source file in a docstring formatted in reStructuredText
Parameters: - fname (string) – File name, relative to environment variable
${TRACER_DIR}
- fpointer (function pointer) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging, for example - lrange (string) – Line range to include, similar to Sphinx literalinclude directive
For example:
def func(): """ This is a docstring. This file shows how to use it: .. =[=cog .. import docs.support.incfile .. docs.support.incfile.incfile('func_example.py', cog.out) .. =]= .. code-block:: python # func_example.py if __name__ == '__main__': func() .. =[=end=]= """ return 'This is func output'
- fname (string) – File name, relative to environment variable
-
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] | Tox configuration largely inspired by Ionel’s codelog |
Changelog¶
- 0.9.1rc1 [2015-11-30]: Initial public release
License¶
The MIT License (MIT)
Copyright (c) 2013-2015 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.
Changelog¶
- 0.9.1rc1 [2015-11-30]: Initial public release
eng module¶
This module provides engineering-related functions including:
Handling numbers represented in engineering notation, obtaining their constituent components and converting to and from regular floats. For example:
>>> import putil.eng >>> x = putil.eng.peng(1346, 2, True) >>> x ' 1.35k' >>> putil.eng.peng_float(x) 1350.0 >>> putil.eng.peng_int(x) 1 >>> putil.eng.peng_frac(x) 35 >>> str(putil.eng.peng_mant(x)) '1.35' >>> putil.eng.peng_power(x) EngPower(suffix='k', exp=1000.0) >>> putil.eng.peng_suffix(x) 'k'
Pretty printing Numpy vectors. For example:
>>> from __future__ import print_function >>> import putil.eng >>> header = 'Vector: ' >>> data = [1e-3, 20e-6, 30e+6, 4e-12, 5.25e3, -6e-9, 70, 8, 9] >>> print( ... header+putil.eng.pprint_vector( ... data, ... width=30, ... eng=True, ... frac_length=1, ... limit=True, ... indent=len(header) ... ) ... ) Vector: [ 1.0m, 20.0u, 30.0M, ... 70.0 , 8.0 , 9.0 ]
Formatting numbers represented in scientific notation with a greater degree of control and options than standard Python string formatting. For example:
>>> import putil.eng >>> putil.eng.to_scientific_string( ... number=99.999, ... frac_length=1, ... exp_length=2, ... sign_always=True ... ) '+1.0E+02'
Named tuples¶
-
putil.eng.
ENGPOWER
(suffix, exp)¶ Constructor for engineering notation suffix
-
putil.eng.
NUMCOMP
(mant, exp)¶ Constructor for number components representation
Functions¶
-
putil.eng.
no_exp
(number)¶ Converts a number to a string guaranteeing that the result is not expressed in scientific notation
Parameters: number (integer or float) – Number to convert Return type: string Raises: RuntimeError (Argument `number` is not valid)
-
putil.eng.
peng
(number, frac_length, rjust=True)¶ Converts a number to engineering notation. The absolute value of the number (if it is not exactly zero) is bounded to the interval [1E-24, 1E+24)
Parameters: - number (integer or float) – Number to convert
- frac_length (NonNegativeInteger) – Number of digits of fractional part
- rjust (boolean) – Flag that indicates whether the number is right-justified (True) or not (False)
Return type: string
Raises: - RuntimeError (Argument `frac_length` is not valid)
- RuntimeError (Argument `number` is not valid)
- RuntimeError (Argument `rjust` is not valid)
The supported engineering suffixes are:
Exponent Name Suffix 1E-24 yocto y 1E-21 zepto z 1E-18 atto a 1E-15 femto f 1E-12 pico p 1E-9 nano n 1E-6 micro u 1E-3 milli m 1E+0 1E+3 kilo k 1E+6 mega M 1E+9 giga G 1E+12 tera T 1E+15 peta P 1E+18 exa E 1E+21 zetta Z 1E+24 yotta Y For example:
>>> import putil.eng >>> putil.eng.peng(1235.6789E3, 3, False) '1.236M'
-
putil.eng.
peng_float
(snum)¶ Returns the floating point equivalent of a number represented in engineering notation
Parameters: snum (EngineeringNotationNumber) – Number Return type: string Raises: RuntimeError (Argument `snum` is not valid) For example:
>>> import putil.eng >>> putil.eng.peng_float(putil.eng.peng(1235.6789E3, 3, False)) 1236000.0
-
putil.eng.
peng_frac
(snum)¶ Returns the fractional part of a number represented in engineering notation
Parameters: snum (EngineeringNotationNumber) – Number Return type: integer Raises: RuntimeError (Argument `snum` is not valid) For example:
>>> import putil.eng >>> putil.eng.peng_frac(putil.eng.peng(1235.6789E3, 3, False)) 236
-
putil.eng.
peng_int
(snum)¶ Returns the integer part of a number represented in engineering notation
Parameters: snum (EngineeringNotationNumber) – Number Return type: integer Raises: RuntimeError (Argument `snum` is not valid) For example:
>>> import putil.eng >>> putil.eng.peng_int(putil.eng.peng(1235.6789E3, 3, False)) 1
-
putil.eng.
peng_mant
(snum)¶ Returns the mantissa of a number represented in engineering notation
Parameters: snum (EngineeringNotationNumber) – Number Return type: float Raises: RuntimeError (Argument `snum` is not valid) For example:
>>> import putil.eng >>> putil.eng.peng_mant(putil.eng.peng(1235.6789E3, 3, False)) 1.236
-
putil.eng.
peng_power
(snum)¶ Returns engineering suffix and floating point equivalent of the suffix when a number is represented in engineering notation. putil.eng.peng() lists the correspondence between suffix and floating point exponent.
Parameters: snum (EngineeringNotationNumber) – Number Return type: named tuple in which the first item is the engineering suffix and the second item is the floating point equivalent of the suffix when the number is represented in engineering notation. Raises: RuntimeError (Argument `snum` is not valid) For example:
>>> import putil.eng >>> putil.eng.peng_power(putil.eng.peng(1235.6789E3, 3, False)) EngPower(suffix='M', exp=1000000.0)
-
putil.eng.
peng_suffix
(snum)¶ Returns the suffix of a number represented in engineering notation
Parameters: snum (EngineeringNotationNumber) – Number Return type: string Raises: RuntimeError (Argument `snum` is not valid) For example:
>>> import putil.eng >>> putil.eng.peng_suffix(putil.eng.peng(1235.6789E3, 3, False)) 'M'
-
putil.eng.
peng_suffix_math
(suffix, offset)¶ Returns an engineering suffix based on a starting suffix and an offset of number of suffixes
Parameters: - suffix (EngineeringNotationSuffix) – Engineering suffix
- offset (integer) – Engineering suffix offset
Return type: string
Raises: - RuntimeError (Argument `offset` is not valid)
- RuntimeError (Argument `suffix` is not valid)
- ValueError (Argument `offset` is not valid)
For example:
>>> import putil.eng >>> putil.eng.peng_suffix_math('u', 6) 'T'
-
putil.eng.
pprint_vector
(vector, limit=False, width=None, indent=0, eng=False, frac_length=3)¶ Formats a list of numbers (vector) or a Numpy vector for printing. If the argument vector is
None
the string'None'
is returnedParameters: - vector (list of integers or floats, Numpy vector or None) – Vector to pretty print or None
- limit (boolean) – Flag that indicates whether at most 6 vector items are printed (all vector items if its length is equal or less than 6, first and last 3 vector items if it is not) (True), or the entire vector is printed (False)
- width (integer or None) – Number of available characters per line. If None the vector is printed in one line
- indent (boolean) – Flag that indicates whether all subsequent lines after the first one are indented (True) or not (False). Only relevant if width is not None
- eng (boolean) – Flag that indicates whether engineering notation is used (True) or not (False)
- frac_length (integer) – Number of digits of fractional part (only applicable if eng is True)
Raises: ValueError (Argument `width` is too small)
Return type: string
For example:
>>> from __future__ import print_function >>> import putil.eng >>> header = 'Vector: ' >>> data = [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9] >>> print( ... header+putil.eng.pprint_vector( ... data, ... width=30, ... eng=True, ... frac_length=1, ... limit=True, ... indent=len(header) ... ) ... ) Vector: [ 1.0m, 20.0u, 300.0M, ... 700.0 , 8.0 , 9.0 ] >>> print( ... header+putil.eng.pprint_vector( ... data, ... width=30, ... eng=True, ... frac_length=0, ... indent=len(header) ... ) ... ) Vector: [ 1m, 20u, 300M, 4p, 5k, -6n, 700 , 8 , 9 ] >>> print(putil.eng.pprint_vector(data, eng=True, frac_length=0)) [ 1m, 20u, 300M, 4p, 5k, -6n, 700 , 8 , 9 ] >>> print(putil.eng.pprint_vector(data, limit=True)) [ 0.001, 2e-05, 300000000.0, ..., 700, 8, 9 ]
-
putil.eng.
round_mantissa
(arg, decimals=0)¶ Rounds the fractional part of a floating point number mantissa or Numpy vector of floating point numbers to a given number of digits. Integers are not altered. The mantissa used is that of the floating point number(s) when expressed in normalized scientific notation
Parameters: - arg (integer, float, Numpy vector of integers or floats, or None) – Input data
- decimals (integer) – Number of digits to round the fractional part of the mantissa to.
Return type: same as arg
For example:
>>> import putil.eng >>> putil.eng.round_mantissa(012345678E-6, 3) 12.35 >>> putil.eng.round_mantissa(5, 3) 5
-
putil.eng.
to_scientific_string
(number, frac_length=None, exp_length=None, sign_always=False)¶ Converts a number or a string representing a number to a string with the number expressed in scientific notation. Full precision is maintained if the number is represented as a string
Parameters: - number (number or string) – Number to convert
- frac_length (integer or None) – Number of digits of fractional part, None indicates that the fractional part of the number should not be limited
- exp_length (integer or None) – Number of digits of the exponent; the actual length of the exponent takes precedence if it is longer
- sign_always (boolean) – Flag that indicates whether the sign always precedes the number for both non-negative and negative numbers (True) or only for negative numbers (False)
Return type: string
For example:
>>> import putil.eng >>> putil.eng.to_scientific_string(333) '3.33E+2' >>> putil.eng.to_scientific_string(0.00101) '1.01E-3' >>> putil.eng.to_scientific_string(99.999, 1, 2, True) '+1.0E+02'
-
putil.eng.
to_scientific_tuple
(number)¶ Returns mantissa and exponent of a number when expressed in scientific notation. Full precision is maintained if the number is represented as a string
Parameters: number (integer, float or string) – Number Return type: named tuple in which the first item is the mantissa (string) and the second item is the exponent (integer) of the number when expressed in scientific notation For example:
>>> import putil.eng >>> putil.eng.to_scientific_tuple('135.56E-8') NumComp(mant='1.3556', exp=-6) >>> putil.eng.to_scientific_tuple(0.0000013556) NumComp(mant='1.3556', exp=-6)
exdoc module¶
This module can be used to automatically generate exceptions documentation marked up in reStructuredText with help from cog and the putil.exh module.
The exceptions to auto-document need to be “traced” before the documentation is generated; in general tracing consists of calling the methods, functions and/or class properties so that all the required putil.exh.ExHandle.add_exception() calls are covered (exceptions generated by contracts defined using the putil.pcontracts module are automatically traced when the contracts are checked). 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 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, putil.exdoc
def trace_module(no_print=True):
""" Trace my_module exceptions """
pwd = os.path.dirname(__file__)
script_name = repr(os.path.join(pwd, 'test_my_module.py'))
with putil.exdoc.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 putil.exdoc.ExDocCxt sets up the tracing environment and returns a putil.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, putil.exdoc, docs.support.my_module
def trace_module(no_print=True):
""" Trace my_module_original exceptions """
with putil.exdoc.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):
# my_module.py
# Exception tracing initialization code
"""
[[[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]]]
"""
import putil.exh
def func(name):
r"""
Prints your name
:param name: Name to print
:type name: string
.. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]]
.. [[[end]]]
"""
exhobj = putil.exh.get_or_create_exh_obj()
exhobj.add_exception(
exname='illegal_name',
extype=TypeError,
exmsg='Argument `name` is not valid'
)
exhobj.raise_exception_if(
exname='illegal_name',
condition=not isinstance(name, str)
)
return 'My name is {0}'.format(name)
class MyClass(object):
"""
Stores a value
:param value: value
:type value: integer
.. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]]
.. [[[end]]]
"""
def __init__(self, value=None):
self._exhobj = putil.exh.get_or_create_exh_obj()
self._value = None if not value else value
def _get_value(self):
self._exhobj.add_exception(
exname='not_set',
extype=RuntimeError,
exmsg='Attribute `value` not set'
)
self._exhobj.raise_exception_if(
exname='not_set',
condition=not self._value
)
return self._value
def _set_value(self, value):
self._exhobj.add_exception(
exname='illegal',
extype=RuntimeError,
exmsg='Argument `value` is not valid'
)
self._exhobj.raise_exception_if(
exname='illegal',
condition=not isinstance(value, int)
)
self._value = value
value = property(_get_value, _set_value)
r"""
Sets or returns 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:
# my_module_ref.py
# Exception tracing initialization code
"""
[[[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]]]
"""
import putil.exh
def func(name):
r"""
Prints 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]]]
"""
exhobj = putil.exh.get_or_create_exh_obj()
exhobj.add_exception(
exname='illegal_name',
extype=TypeError,
exmsg='Argument `name` is not valid'
)
exhobj.raise_exception_if(
exname='illegal_name',
condition=not isinstance(name, str)
)
return 'My name is {0}'.format(name)
class MyClass(object):
"""
Stores a value
:param value: value
:type value: integer
.. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]]
.. [[[end]]]
"""
def __init__(self, value=None):
self._exhobj = putil.exh.get_or_create_exh_obj()
self._value = None if not value else value
def _get_value(self):
self._exhobj.add_exception(
exname='not_set',
extype=RuntimeError,
exmsg='Attribute `value` not set'
)
self._exhobj.raise_exception_if(
exname='not_set',
condition=not self._value
)
return self._value
def _set_value(self, value):
self._exhobj.add_exception(
exname='illegal',
extype=RuntimeError,
exmsg='Argument `value` is not valid'
)
self._exhobj.raise_exception_if(
exname='illegal',
condition=not isinstance(value, int)
)
self._value = value
value = property(_get_value, _set_value)
r"""
Sets or returns 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 putil.exdoc.ExDoc.get_sphinx_autodoc(). Properties defined by other methods can still be auto-documented with putil.exdoc.ExDoc.get_sphinx_doc() and explicitly providing the method/function name.
Context managers¶
-
class
putil.exdoc.
ExDocCxt
(exclude=None, pickle_fname=None, in_callables_fname=None, out_callables_fname=None)¶ Bases: object
Context manager to simplify exception tracing; it sets up the tracing environment and returns a putil.exdoc.ExDoc object that can the be used in the documentation string of each callable to extract the exceptions documentation with either putil.exdoc.ExDoc.get_sphinx_doc() or putil.exdoc.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 putil.pinspect.Callables.save() or putil.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:
>>> from __future__ import print_function >>> import putil.eng, putil.exdoc >>> with putil.exdoc.ExDocCxt() as exdoc_obj: ... value = putil.eng.peng(1e6, 3, False) >>> print(exdoc_obj.get_sphinx_doc('putil.eng.peng')) .. Auto-generated exceptions documentation for putil.eng.peng :raises: * RuntimeError (Argument \`frac_length\` is not valid) * RuntimeError (Argument \`number\` is not valid) * RuntimeError (Argument \`rjust\` is not valid)
Classes¶
-
class
putil.exdoc.
ExDoc
(exh_obj, depth=None, exclude=None)¶ Bases: object
Generates exception documentation with reStructuredText mark-up
Parameters: - exh_obj (putil.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 putil.exdoc.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 putil.exdoc.ExDoc.exclude). If None all callables are included
Return type: 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)¶ Returns an exception list marked up in reStructuredText automatically determining callable name
Parameters: - depth (non-negative integer or None) – Hierarchy levels to include in the exceptions list (overrides default depth argument; see putil.exdoc.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 putil.exdoc.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)
Raises: - RuntimeError (Argument `depth` is not valid)
- RuntimeError (Argument `error` is not valid)
- RuntimeError (Argument `exclude` 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)¶ Returns 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 putil.exdoc.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 putil.exdoc.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)
Raises: - RuntimeError (Argument `depth` is not valid)
- RuntimeError (Argument `error` is not valid)
- RuntimeError (Argument `exclude` is not valid)
- RuntimeError (Argument `raised` is not valid)
- RuntimeError (Argument `width` is not valid)
- RuntimeError (Callable not found in exception list: [name])
-
depth
¶ Gets or sets 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
¶ Gets or sets the default list of (potentially partial) module and callable names to exclude from exceptions per callable. For example,
['putil.ex']
excludes all exceptions from modules putil.exh and putil.exdoc (it acts asr'putil.ex*'
). In addition to these modules,['putil.ex', 'putil.eng.peng']
excludes exceptions from the function putil.eng.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
import putil.exh
EXHOBJ = putil.exh.ExHandle()
def my_func(name):
""" Sample function """
EXHOBJ.add_exception(
exname='illegal_name',
extype=TypeError,
exmsg='Argument `name` is not valid'
)
EXHOBJ.raise_exception_if(
exname='illegal_name',
condition=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/registering
an exception with putil.exh.ExHandle.add_exception() and
conditionally raising it with putil.exh.ExHandle.raise_exception_if()
takes the same number of lines of code as an exception raised inside an
if
block and incurs a slight performance penalty, using the
putil.exh module allows for automatic documentation of the exceptions
raised by any function, method or class property with the help of the
putil.exdoc module.
Functions¶
-
putil.exh.
get_exh_obj
()¶ Returns the global exception handler
Return type: putil.exh.ExHandle if global exception handler is set, None otherwise
-
putil.exh.
get_or_create_exh_obj
(full_cname=False, exclude=None, callables_fname=None)¶ Returns the global exception handler if it is set, otherwise creates a new global exception handler and returns it
Parameters: - full_cname (boolean) –
Flag that indicates whether fully qualified function/method/class property names are obtained for functions/methods/class properties that use the exception manager (True) or not (False).
There is a performance penalty if the flag is True as the call stack needs to be traced. This argument is only relevant if the global exception handler is not set and a new one is created
- 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
- callables_fname (FileNameExists or None) – File name that contains traced modules information. File can be produced by either the putil.pinspect.Callables.save() or putil.exh.ExHandle.save_callables() methods
Return type: Raises: - OSError (File [callables_fname] could not be found
- RuntimeError (Argument `exclude` is not valid)
- RuntimeError (Argument `callables_fname` is not valid)
- RuntimeError (Argument `full_cname` is not valid)
- full_cname (boolean) –
-
putil.exh.
del_exh_obj
()¶ Deletes global exception handler (if set)
-
putil.exh.
set_exh_obj
(obj)¶ Sets the global exception handler
Parameters: obj (putil.exh.ExHandle) – Exception handler Raises: RuntimeError (Argument `obj` is not valid)
Classes¶
-
class
putil.exh.
ExHandle
(full_cname=False, exclude=None, callables_fname=None)¶ Bases: object
Exception handler
Parameters: - full_cname (boolean) –
Flag that indicates whether fully qualified function/method/class property names are obtained for functions/methods/class properties that use the exception manager (True) or not (False).
There is a performance penalty if the flag is True as the call stack needs to be traced
- 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
- callables_fname (FileNameExists or None) – File name that contains traced modules information. File can be produced by either the putil.pinspect.Callables.save() or putil.exh.ExHandle.save_callables() methods
Return type: Raises: - OSError (File [callables_fname] could not be found
- RuntimeError (Argument `exclude` is not valid)
- RuntimeError (Argument `callables_fname` is not valid)
- RuntimeError (Argument `full_cname` is not valid)
- ValueError (Source for module [module_name] could not be found)
-
__add__
(other)¶ Merges two objects.
Raises: - RuntimeError (Incompatible exception handlers)
- TypeError (Unsupported operand type(s) for +: putil.exh.ExHandle and [other_type])
For example:
>>> import copy, putil.exh, putil.eng, putil.tree >>> exhobj = putil.exh.set_exh_obj(putil.exh.ExHandle()) >>> putil.eng.peng(100, 3, True) ' 100.000 ' >>> tobj = putil.tree.Tree().add_nodes([{'name':'a', 'data':5}]) >>> obj1 = copy.copy(putil.exh.get_exh_obj()) >>> putil.exh.del_exh_obj() >>> exhobj = putil.exh.get_or_create_exh_obj() >>> putil.eng.peng(100, 3, True) # Trace some exceptions ' 100.000 ' >>> obj2 = copy.copy(putil.exh.get_exh_obj()) >>> putil.exh.del_exh_obj() >>> exhobj = putil.exh.get_or_create_exh_obj() >>> tobj = putil.tree.Tree().add_nodes([{'name':'a', 'data':5}]) >>> obj3 = copy.copy(putil.exh.get_exh_obj()) >>> obj1 == obj2 False >>> obj1 == obj3 False >>> obj1 == obj2+obj3 True
-
__bool__
()¶ Returns
False
if exception handler does not have any exception defined,True
otherwise.Note
This method applies to Python 3.x
For example:
>>> from __future__ import print_function >>> import putil.exh >>> obj = putil.exh.ExHandle() >>> if obj: ... print('Boolean test returned: True') ... else: ... print('Boolean test returned: False') Boolean test returned: False >>> def my_func(exhobj): ... exhobj.add_exception('test', RuntimeError, 'Message') >>> my_func(obj) >>> if obj: ... print('Boolean test returned: True') ... else: ... print('Boolean test returned: False') Boolean test returned: True
-
__copy__
()¶ Copies object. For example:
>>> import copy, putil.exh, putil.eng >>> exhobj = putil.exh.set_exh_obj(putil.exh.ExHandle()) >>> putil.eng.peng(100, 3, True) ' 100.000 ' >>> obj1 = putil.exh.get_exh_obj() >>> obj2 = copy.copy(obj1) >>> obj1 == obj2 True
-
__eq__
(other)¶ Tests object equality. For example:
>>> import copy, putil.exh, putil.eng >>> exhobj = putil.exh.set_exh_obj(putil.exh.ExHandle()) >>> putil.eng.peng(100, 3, True) ' 100.000 ' >>> obj1 = putil.exh.get_exh_obj() >>> obj2 = copy.copy(obj1) >>> obj1 == obj2 True >>> 5 == obj1 False
-
__iadd__
(other)¶ Merges an object into an existing object.
Raises: - RuntimeError (Incompatible exception handlers)
- TypeError (Unsupported operand type(s) for +: putil.exh.ExHandle and [other_type])
For example:
>>> import copy, putil.exh, putil.eng, putil.tree >>> exhobj = putil.exh.set_exh_obj(putil.exh.ExHandle()) >>> putil.eng.peng(100, 3, True) ' 100.000 ' >>> tobj = putil.tree.Tree().add_nodes([{'name':'a', 'data':5}]) >>> obj1 = copy.copy(putil.exh.get_exh_obj()) >>> putil.exh.del_exh_obj() >>> exhobj = putil.exh.get_or_create_exh_obj() >>> putil.eng.peng(100, 3, True) # Trace some exceptions ' 100.000 ' >>> obj2 = copy.copy(putil.exh.get_exh_obj()) >>> putil.exh.del_exh_obj() >>> exhobj = putil.exh.get_or_create_exh_obj() >>> tobj = putil.tree.Tree().add_nodes([{'name':'a', 'data':5}]) >>> obj3 = copy.copy(putil.exh.get_exh_obj()) >>> obj1 == obj2 False >>> obj1 == obj3 False >>> obj2 += obj3 >>> obj1 == obj2 True
-
__nonzero__
()¶ Returns
False
if exception handler does not have any exception defined,True
otherwise.Note
This method applies to Python 2.7
For example:
>>> from __future__ import print_function >>> import putil.exh >>> obj = putil.exh.ExHandle() >>> if obj: ... print('Boolean test returned: True') ... else: ... print('Boolean test returned: False') Boolean test returned: False >>> def my_func(exhobj): ... exhobj.add_exception('test', RuntimeError, 'Message') >>> my_func(obj) >>> if obj: ... print('Boolean test returned: True') ... else: ... print('Boolean test returned: False') Boolean test returned: True
-
__str__
()¶ Returns a string with a detailed description of the object’s contents. For example:
>>> from __future__ import print_function >>> import docs.support.exh_example >>> docs.support.exh_example.my_func('Tom') My name is Tom >>> print(str(docs.support.exh_example.EXHOBJ)) Name : .../illegal_name Type : TypeError Message : Argument `name` is not valid Function: None
-
add_exception
(exname, extype, exmsg)¶ Adds an exception to the handler
Parameters: - exname (string) – Exception name; has to be unique within the namespace, duplicates are eliminated
- 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
putil.exh.ExHandle.raise_exception_if().
A field starts with the characters
'
- full_cname (boolean) –