PyPI version License Python versions supported Format

Continuous integration test status Continuous integration test coverage Documentation status

Description

This module contains 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, string functions and functions to aid in the unit testing of modules Pytest is the supported test runner

Interpreter

The package has been developed and tested with Python 3.5, 3.6, 3.7 and 3.8 under Linux (Debian, Ubuntu), Apple macOS and Microsoft Windows

Installing

$ pip install pmisc

Documentation

Available at Read the Docs

Contributing

  1. Abide by the adopted code of conduct

  2. Fork the repository from GitHub and then clone personal copy [1]:

    $ github_user=myname
    $ git clone --recurse-submodules \
          https://github.com/"${github_user}"/pmisc.git
    Cloning into 'pmisc'...
    ...
    $ cd pmisc || exit 1
    $ export PMISC_DIR=${PWD}
    $
    
  3. 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 the pypkg 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 "${PMISC_DIR}" || exit 1
    $ pre-commit install
    pre-commit installed at .../pmisc/.git/hooks/pre-commit
    $
    
  4. Ensure that the Python interpreter can find the package modules (update the $PYTHONPATH environment variable, or use sys.paths(), etc.)

    $ export PYTHONPATH=${PYTHONPATH}:${PMISC_DIR}
    $
    
  5. Install the dependencies (if needed, done automatically by pip):

  6. Implement a new feature or fix a bug

  7. 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=pmisc tox
    GLOB sdist-make: .../pmisc/setup.py
    py35-pkg create: .../pmisc/.tox/py35
    py35-pkg installdeps: -r.../pmisc/requirements/tests_py35.pip, -r.../pmisc/requirements/docs_py35.pip
    ...
      py35-pkg: commands succeeded
      py36-pkg: commands succeeded
      py37-pkg: commands succeeded
      py38-pkg: commands succeeded
      congratulations :)
    $
    

    Setuptools can also be used (Tox is configured as its virtual environment manager):

    $ PKG_NAME=pmisc python setup.py tests
    running tests
    running egg_info
    writing pmisc.egg-info/PKG-INFO
    writing dependency_links to pmisc.egg-info/dependency_links.txt
    writing requirements to pmisc.egg-info/requires.txt
    ...
      py35-pkg: commands succeeded
      py36-pkg: commands succeeded
      py37-pkg: commands succeeded
      py38-pkg: commands succeeded
      congratulations :)
    $
    

    Tox (or Setuptools via Tox) runs with the following default environments: py35-pkg, py36-pkg, py37-pkg and py38-pkg [3]. These use the 3.5, 3.6, 3.7 and 3.8 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=pmisc tox -e py35-pkg -- -n 4
    GLOB sdist-make: .../pmisc/setup.py
    py35-pkg inst-nodeps: .../pmisc/.tox/.tmp/package/1/pmisc-1.5.10.zip
    ...
      py35-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=pmisc python setup.py tests -a "-e py35-pkg -- -n 4"
    running tests
    ...
      py35-pkg: commands succeeded
      congratulations :)
    $
    

    There are other convenience environments defined for Tox [3]:

    • py35-repl, py36-repl, py37-repl and py38-repl run the Python 3.5, 3.6, 3.7 and 3.8 REPL, respectively, in the appropriate virtual environment. The pmisc 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 (--).

    • py35-test, py36-test, py37-test and py38-test run Pytest using the Python 3.5, 3.6, 3.7 and 3.8 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=pmisc tox -e py35-test -- -x test_pmisc.py
      GLOB sdist-make: .../pmisc/setup.py
      py35-pkg inst-nodeps: .../pmisc/.tox/.tmp/package/1/pmisc-1.5.10.zip
      ...
        py35-pkg: commands succeeded
        congratulations :)
      $
      
    • py35-test, py36-test, py37-test and py38-test test code and branch coverage using the 3.5, 3.6, 3.7 and 3.8 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 ${PMISC_DIR}/.tox/py[PV]/usr/share/pmi sc/tests/htmlcov/index.html where [PV] stands for 3.5, 3.6, 3.7 or 3.8 depending on the interpreter used.

  8. Verify that continuous integration tests pass. The package has continuous integration configured for Linux, Apple macOS and Microsoft Windows (all via Azure DevOps).

  9. Document the new feature or bug fix (if needed). The script ${PMISC_DIR}/pypkg/build_docs.py re-builds the whole package documentation (re-generates images, cogs source files, etc.):

    $ "${PMISC_DIR}"/pypkg/build_docs.py -h
    usage: build_docs.py [-h] [-d DIRECTORY] [-r]
                         [-n NUM_CPUS] [-t]
    
    Build pmisc package documentation
    
    optional arguments:
      -h, --help            show this help message and exit
      -d DIRECTORY, --directory DIRECTORY
                            specify source file directory
                            (default ../pmisc)
      -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.5.10 [2020-01-21]: Documentation update
  • 1.5.9 [2020-01-21]: Dropped support for Python 2.7. Added testing for Python
    3.8. Fixed CI bugs under Microsoft Windows. Added more granular argument checks in assert_ro_prop API. Fixed bugs with assert_ro_prop API in new(er) Pytest versions
  • 1.5.8 [2019-03-21]: Minor documentation update
  • 1.5.7 [2019-03-21]: Small enhancement to ste API to make it more flexible.
  • 1.5.6 [2019-03-16]: Suppress warnings while extracting exception message
  • 1.5.5 [2019-03-02]: Fixed bug affecting pytest-pmisc plugin
  • 1.5.4 [2019-03-01]: Abstracted package management to a lightweight framework
  • 1.5.3 [2019-02-25]: Package management updates
  • 1.5.2 [2019-02-15]: Continuous integration bug fix
  • 1.5.1 [2019-02-15]: Minor documentation update
  • 1.5.0 [2019-02-15]: Dropped support for Python 2.6, 3.3 and 3.4. Updates to support newest versions of dependencies
  • 1.4.2 [2018-03-01]: Fixed bugs in gcd and per functions which were not correctly handling Numpy data types. Minor code refactoring
  • 1.4.1 [2018-02-18]: Moved traceback shortening functions to test module so as to enable the pytest-pmisc Pytest plugin to shorten the tracebacks of the test module functions in that environment
  • 1.4.0 [2018-02-16]: Shortened traceback of test methods to point only to the line that uses the function that generates the exception
  • 1.3.1 [2018-01-18]: Minor package build fix
  • 1.3.0 [2018-01-18]: Dropped support for Python interpreter versions 2.6, 3.3 and 3.4. Updated dependencies versions to their current versions. Fixed failing tests under newer Pytest versions
  • 1.2.2 [2017-02-09]: Package build enhancements and fixes
  • 1.2.1 [2017-02-07]: Python 3.6 support
  • 1.2.0 [2016-10-28]: Added TmpDir context manager to work with temporary directories
  • 1.1.9 [2016-09-26]: Minor documentation update
  • 1.1.8 [2016-08-27]: Fixed Appveyor-CI failures
  • 1.1.7 [2016-08-24]: Fixed Travis-CI failures
  • 1.1.6 [2016-08-24]: Fixed Py.test 3.0.x-related incompatibilities
  • 1.1.5 [2016-08-24]: assert_exception now prints better message when actual exception is different than expected exception
  • 1.1.4 [2016-08-06]: assert_exception now prints traceback when exception raised is different than expected exception
  • 1.1.3 [2016-06-09]: assert_exception exception message is now not limited to just strings
  • 1.1.2 [2016-06-01]: Fixed continuous integration failures in term_echo function testing
  • 1.1.1 [2016-06-01]: Enhanced TmpFile context manager by allowing positional and keyword arguments to be passed to optional write function
  • 1.1.0 [2016-05-15]: Added incfile, ste and term_echo functions. These produce output marked up in reStructuredText of source files (incfile) or terminal commands (ste, term_echo). All can be used to include relevant information in docstrings to enhance documentation
  • 1.0.5 [2016-05-13]: Minor documentation update
  • 1.0.4 [2016-05-02]: Minor documentation and testing enhancements
  • 1.0.3 [2016-04-26]: Dependencies fixes
  • 1.0.2 [2016-04-26]: Windows continuous integration fixes
  • 1.0.1 [2016-04-26]: Removed dependency on Numpy
  • 1.0.0 [2016-04-23]: Final release of 1.0.0 branch
  • 1.0.0rc1 [2016-04-22]: Initial commit, merges misc and test modules of putil PyPI package

License

The MIT License (MIT)

Copyright (c) 2013-2020 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

PyPI version License Python versions supported Format

Continuous integration test status Continuous integration test coverage Documentation status

Description

This module contains 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, string functions and functions to aid in the unit testing of modules Pytest is the supported test runner

Interpreter

The package has been developed and tested with Python 3.5, 3.6, 3.7 and 3.8 under Linux (Debian, Ubuntu), Apple macOS and Microsoft Windows

Installing

$ pip install pmisc

Documentation

Available at Read the Docs

Contributing

  1. Abide by the adopted code of conduct

  2. Fork the repository from GitHub and then clone personal copy [1]:

    $ github_user=myname
    $ git clone --recurse-submodules \
          https://github.com/"${github_user}"/pmisc.git
    Cloning into 'pmisc'...
    ...
    $ cd pmisc || exit 1
    $ export PMISC_DIR=${PWD}
    $
    
  3. 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 the pypkg 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 "${PMISC_DIR}" || exit 1
    $ pre-commit install
    pre-commit installed at .../pmisc/.git/hooks/pre-commit
    $
    
  4. Ensure that the Python interpreter can find the package modules (update the $PYTHONPATH environment variable, or use sys.paths(), etc.)

    $ export PYTHONPATH=${PYTHONPATH}:${PMISC_DIR}
    $
    
  5. Install the dependencies (if needed, done automatically by pip):

  6. Implement a new feature or fix a bug

  7. 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=pmisc tox
    GLOB sdist-make: .../pmisc/setup.py
    py35-pkg create: .../pmisc/.tox/py35
    py35-pkg installdeps: -r.../pmisc/requirements/tests_py35.pip, -r.../pmisc/requirements/docs_py35.pip
    ...
      py35-pkg: commands succeeded
      py36-pkg: commands succeeded
      py37-pkg: commands succeeded
      py38-pkg: commands succeeded
      congratulations :)
    $
    

    Setuptools can also be used (Tox is configured as its virtual environment manager):

    $ PKG_NAME=pmisc python setup.py tests
    running tests
    running egg_info
    writing pmisc.egg-info/PKG-INFO
    writing dependency_links to pmisc.egg-info/dependency_links.txt
    writing requirements to pmisc.egg-info/requires.txt
    ...
      py35-pkg: commands succeeded
      py36-pkg: commands succeeded
      py37-pkg: commands succeeded
      py38-pkg: commands succeeded
      congratulations :)
    $
    

    Tox (or Setuptools via Tox) runs with the following default environments: py35-pkg, py36-pkg, py37-pkg and py38-pkg [3]. These use the 3.5, 3.6, 3.7 and 3.8 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=pmisc tox -e py35-pkg -- -n 4
    GLOB sdist-make: .../pmisc/setup.py
    py35-pkg inst-nodeps: .../pmisc/.tox/.tmp/package/1/pmisc-1.5.10.zip
    ...
      py35-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=pmisc python setup.py tests -a "-e py35-pkg -- -n 4"
    running tests
    ...
      py35-pkg: commands succeeded
      congratulations :)
    $
    

    There are other convenience environments defined for Tox [3]:

    • py35-repl, py36-repl, py37-repl and py38-repl run the Python 3.5, 3.6, 3.7 and 3.8 REPL, respectively, in the appropriate virtual environment. The pmisc 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 (--).

    • py35-test, py36-test, py37-test and py38-test run Pytest using the Python 3.5, 3.6, 3.7 and 3.8 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=pmisc tox -e py35-test -- -x test_pmisc.py
      GLOB sdist-make: .../pmisc/setup.py
      py35-pkg inst-nodeps: .../pmisc/.tox/.tmp/package/1/pmisc-1.5.10.zip
      ...
        py35-pkg: commands succeeded
        congratulations :)
      $
      
    • py35-test, py36-test, py37-test and py38-test test code and branch coverage using the 3.5, 3.6, 3.7 and 3.8 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 ${PMISC_DIR}/.tox/py[PV]/usr/share/pmi sc/tests/htmlcov/index.html where [PV] stands for 3.5, 3.6, 3.7 or 3.8 depending on the interpreter used.

  8. Verify that continuous integration tests pass. The package has continuous integration configured for Linux, Apple macOS and Microsoft Windows (all via Azure DevOps).

  9. Document the new feature or bug fix (if needed). The script ${PMISC_DIR}/pypkg/build_docs.py re-builds the whole package documentation (re-generates images, cogs source files, etc.):

    $ "${PMISC_DIR}"/pypkg/build_docs.py -h
    usage: build_docs.py [-h] [-d DIRECTORY] [-r]
                         [-n NUM_CPUS] [-t]
    
    Build pmisc package documentation
    
    optional arguments:
      -h, --help            show this help message and exit
      -d DIRECTORY, --directory DIRECTORY
                            specify source file directory
                            (default ../pmisc)
      -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.5.10 [2020-01-21]: Documentation update
  • 1.5.9 [2020-01-21]: Dropped support for Python 2.7. Added testing for Python
    3.8. Fixed CI bugs under Microsoft Windows. Added more granular argument checks in assert_ro_prop API. Fixed bugs with assert_ro_prop API in new(er) Pytest versions
  • 1.5.8 [2019-03-21]: Minor documentation update
  • 1.5.7 [2019-03-21]: Small enhancement to ste API to make it more flexible.
  • 1.5.6 [2019-03-16]: Suppress warnings while extracting exception message
  • 1.5.5 [2019-03-02]: Fixed bug affecting pytest-pmisc plugin
  • 1.5.4 [2019-03-01]: Abstracted package management to a lightweight framework
  • 1.5.3 [2019-02-25]: Package management updates
  • 1.5.2 [2019-02-15]: Continuous integration bug fix
  • 1.5.1 [2019-02-15]: Minor documentation update
  • 1.5.0 [2019-02-15]: Dropped support for Python 2.6, 3.3 and 3.4. Updates to support newest versions of dependencies
  • 1.4.2 [2018-03-01]: Fixed bugs in gcd and per functions which were not correctly handling Numpy data types. Minor code refactoring
  • 1.4.1 [2018-02-18]: Moved traceback shortening functions to test module so as to enable the pytest-pmisc Pytest plugin to shorten the tracebacks of the test module functions in that environment
  • 1.4.0 [2018-02-16]: Shortened traceback of test methods to point only to the line that uses the function that generates the exception
  • 1.3.1 [2018-01-18]: Minor package build fix
  • 1.3.0 [2018-01-18]: Dropped support for Python interpreter versions 2.6, 3.3 and 3.4. Updated dependencies versions to their current versions. Fixed failing tests under newer Pytest versions
  • 1.2.2 [2017-02-09]: Package build enhancements and fixes
  • 1.2.1 [2017-02-07]: Python 3.6 support
  • 1.2.0 [2016-10-28]: Added TmpDir context manager to work with temporary directories
  • 1.1.9 [2016-09-26]: Minor documentation update
  • 1.1.8 [2016-08-27]: Fixed Appveyor-CI failures
  • 1.1.7 [2016-08-24]: Fixed Travis-CI failures
  • 1.1.6 [2016-08-24]: Fixed Py.test 3.0.x-related incompatibilities
  • 1.1.5 [2016-08-24]: assert_exception now prints better message when actual exception is different than expected exception
  • 1.1.4 [2016-08-06]: assert_exception now prints traceback when exception raised is different than expected exception
  • 1.1.3 [2016-06-09]: assert_exception exception message is now not limited to just strings
  • 1.1.2 [2016-06-01]: Fixed continuous integration failures in term_echo function testing
  • 1.1.1 [2016-06-01]: Enhanced TmpFile context manager by allowing positional and keyword arguments to be passed to optional write function
  • 1.1.0 [2016-05-15]: Added incfile, ste and term_echo functions. These produce output marked up in reStructuredText of source files (incfile) or terminal commands (ste, term_echo). All can be used to include relevant information in docstrings to enhance documentation
  • 1.0.5 [2016-05-13]: Minor documentation update
  • 1.0.4 [2016-05-02]: Minor documentation and testing enhancements
  • 1.0.3 [2016-04-26]: Dependencies fixes
  • 1.0.2 [2016-04-26]: Windows continuous integration fixes
  • 1.0.1 [2016-04-26]: Removed dependency on Numpy
  • 1.0.0 [2016-04-23]: Final release of 1.0.0 branch
  • 1.0.0rc1 [2016-04-22]: Initial commit, merges misc and test modules of putil PyPI package

License

The MIT License (MIT)

Copyright (c) 2013-2020 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

Context managers

pmisc.ignored(*exceptions)

Execute commands and selectively ignore exceptions.

Inspired by “Transforming Code into Beautiful, Idiomatic Python” talk at PyCon US 2013 by Raymond Hettinger.

Parameters:exceptions (Exception object, i.e. RuntimeError, OSError, etc.) – Exception type(s) to ignore

For example:

# pmisc_example_1.py
from __future__ import print_function
import os, pmisc

def ignored_example():
    fname = 'somefile.tmp'
    open(fname, 'w').close()
    print('File {0} exists? {1}'.format(
        fname, os.path.isfile(fname)
    ))
    with pmisc.ignored(OSError):
        os.remove(fname)
    print('File {0} exists? {1}'.format(
        fname, os.path.isfile(fname)
    ))
    with pmisc.ignored(OSError):
        os.remove(fname)
    print('No exception trying to remove a file that does not exists')
    try:
        with pmisc.ignored(RuntimeError):
            os.remove(fname)
    except:
        print('Got an exception')
>>> import docs.support.pmisc_example_1
>>> docs.support.pmisc_example_1.ignored_example()
File somefile.tmp exists? True
File somefile.tmp exists? False
No exception trying to remove a file that does not exists
Got an exception
class pmisc.Timer(verbose=False)

Bases: object

Time profile of code blocks.

The profiling is done by calculating elapsed time between the context manager entry and exit time points. Inspired by Huy Nguyen’s blog.

Parameters:verbose (boolean) – Flag that indicates whether the elapsed time is printed upon exit (True) or not (False)
Returns:pmisc.Timer
Raises:RuntimeError – Argument `verbose` is not valid

For example:

# pmisc_example_2.py
from __future__ import print_function
import pmisc

def timer(num_tries, fpointer):
    with pmisc.Timer() as tobj:
        for _ in range(num_tries):
            fpointer()
    print('Time per call: {0} seconds'.format(
        tobj.elapsed_time/(2.0*num_tries)
    ))

def sample_func():
    count = 0
    for num in range(0, count):
        count += num
>>> from docs.support.pmisc_example_2 import *
>>> timer(100, sample_func) 
Time per call: ... seconds
elapsed_time

Returns elapsed time (in milliseconds) between context manager entry and exit time points

Return type:float
class pmisc.TmpDir(dpath=None)

Bases: object

Create a temporary (sub)directory.

Parameters:dpath (string or None) – Directory under which temporary (sub)directory is to be created. If None the (sub)directory is created under the default user’s/system temporary directory
Returns:temporary directory absolute path
Raises:RuntimeError – Argument `dpath` is not valid

Warning

The file name returned uses the forward slash (/) as the path separator regardless of the platform. This avoids problems with escape sequences or mistaken Unicode character encodings (\\user for example). Many functions in the os module of the standard library ( os.path.normpath() and others) can change this path separator to the operating system path separator if needed

class pmisc.TmpFile(fpointer=None, *args, **kwargs)

Bases: object

Creates a temporary file that is deleted at context manager exit.

The context manager can optionally set up hooks for a provided function to write data to the created temporary file.

Parameters:
  • fpointer (function object or None) – Pointer to a function that writes data to file. If the argument is not None the function pointed to receives exactly one argument, a file-like object
  • args (any) – Positional arguments for pointer function
  • kwargs (any) – Keyword arguments for pointer function
Returns:

temporary file name

Raises:

RuntimeError – Argument `fpointer` is not valid

Warning

The file name returned uses the forward slash (/) as the path separator regardless of the platform. This avoids problems with escape sequences or mistaken Unicode character encodings (\\user for example). Many functions in the os module of the standard library ( os.path.normpath() and others) can change this path separator to the operating system path separator if needed

For example:

# pmisc_example_3.py
from __future__ import print_function
import pmisc

def write_data(file_handle):
    file_handle.write('Hello world!')

def show_tmpfile():
    with pmisc.TmpFile(write_data) as fname:
        with open(fname, 'r') as fobj:
            lines = fobj.readlines()
    print('\n'.join(lines))
>>> from docs.support.pmisc_example_3 import *
>>> show_tmpfile()
Hello world!

File

pmisc.make_dir(fname)

Create the directory of a fully qualified file name if it does not exist.

Parameters:fname (string) – File name

Equivalent to these Bash shell commands:

$ fname="${HOME}/mydir/myfile.txt"
$ dir=$(dirname "${fname}")
$ mkdir -p "${dir}"
Parameters:fname (string) – Fully qualified file name
pmisc.normalize_windows_fname(fname)

Fix potential problems with a Microsoft Windows file name.

Superfluous backslashes are removed and unintended escape sequences are converted to their equivalent (presumably correct and intended) representation, for example r'\\x07pps' is transformed to r'\\\\apps'. A file name is considered network shares if the file does not include a drive letter and they start with a double backslash ('\\\\')

Parameters:fname (string) – File name
Return type:string

Membership

pmisc.isalpha(obj)

Test if the argument is a string representing a number.

Parameters:obj (any) – Object
Return type:boolean

For example:

>>> import pmisc
>>> pmisc.isalpha('1.5')
True
>>> pmisc.isalpha('1E-20')
True
>>> pmisc.isalpha('1EA-20')
False
pmisc.ishex(obj)

Test if the argument is a string representing a valid hexadecimal digit.

Parameters:obj (any) – Object
Return type:boolean
pmisc.isiterable(obj)

Test if the argument is an iterable.

Parameters:obj (any) – Object
Return type:boolean
pmisc.isnumber(obj)

Test if the argument is a number (complex, float or integer).

Parameters:obj (any) – Object
Return type:boolean
pmisc.isreal(obj)

Test if the argument is a real number (float or integer).

Parameters:obj (any) – Object
Return type:boolean

Miscellaneous

pmisc.flatten_list(lobj)

Recursively flattens a list.

Parameters:lobj (list) – List to flatten
Return type:list

For example:

>>> import pmisc
>>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7])
[1, 2, 3, 4, 5, 6, 7]

Numbers

pmisc.gcd(vector)

Calculate the greatest common divisor (GCD) of a sequence of numbers.

The sequence can be a list of numbers or a Numpy vector of numbers. The computations are carried out with a precision of 1E-12 if the objects are not fractions. When possible it is best to use the fractions data type with the numerator and denominator arguments when computing the GCD of floating point numbers.

Parameters:vector (list of numbers or Numpy vector of numbers) – Vector of numbers
pmisc.normalize(value, series, offset=0)

Scale a value to the range defined by a series.

Parameters:
  • value (number) – Value to normalize
  • series (list) – List of numbers that defines the normalization range
  • offset (number) – Normalization offset, i.e. the returned value will be in the range [offset, 1.0]
Return type:

number

Raises:
  • RuntimeError – Argument `offset` is not valid
  • RuntimeError – Argument `series` is not valid
  • RuntimeError – Argument `value` is not valid
  • ValueError – Argument `offset` has to be in the [0.0, 1.0] range
  • ValueError – Argument `value` has to be within the bounds of the argument `series`

For example:

>>> import pmisc
>>> pmisc.normalize(15, [10, 20])
0.5
>>> pmisc.normalize(15, [10, 20], 0.5)
0.75
pmisc.per(arga, argb, prec=10)

Calculate percentage difference between numbers.

If only two numbers are given, the percentage difference between them is computed. If two sequences of numbers are given (either two lists of numbers or Numpy vectors), the element-wise percentage difference is computed. If any of the numbers in the arguments is zero the value returned is the maximum floating-point number supported by the Python interpreter.

Parameters:
  • arga (float, integer, list of floats or integers, or Numpy vector of floats or integers) – First number, list of numbers or Numpy vector
  • argb (float, integer, list of floats or integers, or Numpy vector of floats or integers) – Second number, list of numbers or or Numpy vector
  • prec (integer) – Maximum length of the fractional part of the result
Return type:

Float, list of floats or Numpy vector, depending on the arguments type

Raises:
  • RuntimeError – Argument `arga` is not valid
  • RuntimeError – Argument `argb` is not valid
  • RuntimeError – Argument `prec` is not valid
  • TypeError – Arguments are not of the same type
pmisc.pgcd(numa, numb)

Calculate the greatest common divisor (GCD) of two numbers.

Parameters:
  • numa (number) – First number
  • numb (number) – Second number
Return type:

number

For example:

>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5
>>> str(pmisc.pgcd(0.05, 0.02))
'0.01'
>>> str(pmisc.pgcd(5/3.0, 2/3.0))[:6]
'0.3333'
>>> pmisc.pgcd(
...     fractions.Fraction(str(5/3.0)),
...     fractions.Fraction(str(2/3.0))
... )
Fraction(1, 3)
>>> pmisc.pgcd(
...     fractions.Fraction(5, 3),
...     fractions.Fraction(2, 3)
... )
Fraction(1, 3)

reStructuredText

pmisc.incfile(fname, fpointer, lrange=None, sdir=None)

Return a Python source file formatted in reStructuredText.

Parameters:
  • fname (string) – File name, relative to environment variable PKG_DOC_DIR
  • fpointer (function object) – Output function pointer. Normally is cog.out but other functions can be used for debugging
  • lrange (string) – Line range to include, similar to Sphinx literalinclude directive
  • sdir (string) – Source file directory. If None the PKG_DOC_DIR environment variable is used if it is defined, otherwise the directory where the module is located is used

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'
pmisc.ste(command, nindent, mdir, fpointer, env=None)

Print STDOUT of a shell command formatted in reStructuredText.

This is a simplified version of pmisc.term_echo().

Parameters:
  • command (string) – Shell command (relative to mdir if env is not given)
  • nindent (integer) – Indentation level
  • mdir (string) – Module directory, used if env is not given
  • fpointer (function object) – Output function pointer. Normally is cog.out but print or other functions can be used for debugging
  • env (dictionary) – Environment dictionary. If not provided, the environment dictionary is the key “PKG_BIN_DIR” with the value of the mdir

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:: console

$ ${PKG_BIN_DIR}/build_docs.py -h
usage: build_docs.py [-h] [-d DIRECTORY] [-n NUM_CPUS]
...
$

.. ]]]
pmisc.term_echo(command, nindent=0, env=None, fpointer=None, cols=60)

Print STDOUT of a shell command formatted in reStructuredText.

Parameters:
  • command (string) – Shell command
  • nindent (integer) – Indentation level
  • env (dictionary) – Environment variable replacement dictionary. The command is pre-processed and any environment variable represented in the full notation (${...} in Linux and OS X or %...% in Windows) 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 object) – Output function pointer. Normally is cog.out but print or other functions can be used for debugging
  • cols (integer) – Number of columns of output

Strings

pmisc.binary_string_to_octal_string(text)

Return binary-packed octal string aliasing typical codes to their escape sequences.

Parameters:text (string) – Text to convert
Return type:string
Code Alias Description
0 \0 Null character
7 \a Bell / alarm
8 \b Backspace
9 \t Horizontal tab
10 \n Line feed
11 \v Vertical tab
12 \f Form feed
13 \r Carriage return

For example:

>>> import pmisc, struct, sys
>>> def py23struct(num):
...    if sys.hexversion < 0x03000000:
...        return struct.pack('h', num)
...    else:
...        return struct.pack('h', num).decode('ascii')
>>> nums = range(1, 15)
>>> pmisc.binary_string_to_octal_string(
...     ''.join([py23struct(num) for num in nums])
... ).replace('o', '')  #doctest: +ELLIPSIS
'\\1\\0\\2\\0\\3\\0\\4\\0\\5\\0\\6\\0\\a\\0\\b\\0\\t\\0\\...
pmisc.char_to_decimal(text)

Convert a string to its decimal ASCII representation with spaces between characters.

Parameters:text (string) – Text to convert
Return type:string

For example:

>>> import pmisc
>>> pmisc.char_to_decimal('Hello world!')
'72 101 108 108 111 32 119 111 114 108 100 33'
pmisc.elapsed_time_string(start_time, stop_time)

Return a formatted string with the elapsed time between two time points.

The string includes years (365 days), months (30 days), days (24 hours), hours (60 minutes), minutes (60 seconds) and seconds. If both arguments are equal, the string returned is 'None'; otherwise, the string returned is [YY year[s], [MM month[s], [DD day[s], [HH hour[s], [MM minute[s] [and SS second[s]]]]]]. Any part (year[s], month[s], etc.) is omitted if the value of that part is null/zero

Parameters:
  • start_time (datetime) – Starting time point
  • stop_time (datetime) – Ending time point
Return type:

string

Raises:

RuntimeError – Invalid time delta specification

For example:

>>> import datetime, pmisc
>>> start_time = datetime.datetime(2014, 1, 1, 1, 10, 1)
>>> stop_time = datetime.datetime(2015, 1, 3, 1, 10, 3)
>>> pmisc.elapsed_time_string(start_time, stop_time)
'1 year, 2 days and 2 seconds'
pmisc.pcolor(text, color, indent=0)

Return a string that once printed is colorized.

Parameters:
  • text (string) – Text to colorize
  • color (string) – Color to use, one of 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' or 'none' (case insensitive)
  • indent (integer) – Number of spaces to prefix the output with
Return type:

string

Raises:
  • RuntimeError – Argument `color` is not valid
  • RuntimeError – Argument `indent` is not valid
  • RuntimeError – Argument `text` is not valid
  • ValueError – Unknown color [color]
pmisc.quote_str(obj)

Add extra quotes to a string.

If the argument is not a string it is returned unmodified.

Parameters:obj (any) – Object
Return type:Same as argument

For example:

>>> import pmisc
>>> pmisc.quote_str(5)
5
>>> pmisc.quote_str('Hello!')
'"Hello!"'
>>> pmisc.quote_str('He said "hello!"')
'\'He said "hello!"\''
pmisc.strframe(obj, extended=False)

Return a string with a frame record pretty-formatted.

The record is typically an item in a list generated by inspect.stack()).

Parameters:
  • obj (tuple) – Frame record
  • extended (boolean) – Flag that indicates whether contents of the frame object are printed (True) or not (False)
Return type:

string

Test

The module installs a custom exception hook to shorten the traceback of exceptions generated by pmisc.assert_arg_invalid(), pmisc.assert_exception(), pmisc.assert_prop(), pmisc.assert_ro_prop(), and pmisc.compare_strings() so that they end at the line that calls these functions and not the actual line inside these functions that raises the exception. This greatly enhances the readability and usability of these functions, particularly when used with Py.test. The existing exception hook is used when an exception is not one of the expected exceptions generated by the functions listed above.

pmisc.assert_arg_invalid(fpointer, pname, *args, **kwargs)

Test if function raises RuntimeError('Argument `*pname*` is not valid').

*pname* is the value of the pname argument, when called with given positional and/or keyword arguments

Parameters:
  • fpointer (callable) – Object to evaluate
  • pname (string) – Parameter name
  • args (tuple) – Positional arguments to pass to object
  • kwargs (dictionary) – Keyword arguments to pass to object
Raises:
  • AssertionError – Did not raise
  • RuntimeError – Illegal number of arguments
pmisc.assert_exception(fpointer, extype, exmsg, *args, **kwargs)

Assert an exception type and message within the Py.test environment.

If the actual exception message and the expected exception message do not literally match then the expected exception message is treated as a regular expression and a match is sought with the actual exception message

Parameters:
  • fpointer (callable) – Object to evaluate
  • extype (type) – Expected exception type
  • exmsg (any) – Expected exception message (can have regular expressions)
  • args (tuple) – Positional arguments to pass to object
  • kwargs (dictionary) – Keyword arguments to pass to object

For example:

>>> import pmisc
>>> try:
...     pmisc.assert_exception(
...         pmisc.normalize,
...         RuntimeError,
...         'Argument `offset` is not valid',
...         15, [10, 20], 0
...     )   #doctest: +ELLIPSIS
... except:
...     raise RuntimeError('Exception not raised')
Traceback (most recent call last):
    ...
RuntimeError: Exception not raised
Raises:
  • AssertionError – Did not raise
  • RuntimeError – Illegal number of arguments
pmisc.assert_prop(cobj, prop_name, value, extype, exmsg)

Assert whether a class property raises an exception when assigned a value.

Parameters:
  • cobj (class object) – Class object
  • prop_name (string) – Property name
  • extype (Exception type object, i.e. RuntimeError, TypeError, etc.) – Exception type
  • exmsg (string) – Exception message
pmisc.assert_ro_prop(cobj, prop_name)

Assert that a class property cannot be deleted.

Parameters:
  • cobj (class object) – Class object
  • prop_name (string) – Property name
pmisc.compare_strings(actual, ref, diff_mode=False)

Compare two strings.

Lines are numbered, differing characters are colored yellow and extra characters (characters present in one string but not in the other) are colored red

Parameters:
  • actual (string) – Text produced by software under test
  • ref (string) – Reference text
  • diff_mode (boolean) – Flag that indicates whether the line(s) of the actual and reference strings are printed one right after the other (True) of if the actual and reference strings are printed separately (False)
Raises:
  • AssertionError – Strings do not match
  • RuntimeError – Argument `actual` is not valid
  • RuntimeError – Argument `diff_mode` is not valid
  • RuntimeError – Argument `ref` is not valid
pmisc.exception_type_str(exobj)

Return an exception type string.

Parameters:exobj (type (Python 2) or class (Python 3)) – Exception
Return type:string

For example:

>>> import pmisc
>>> pmisc.exception_type_str(RuntimeError)
'RuntimeError'
pmisc.get_exmsg(exobj)

Return exception message (Python interpreter version independent).

Parameters:exobj (exception object) – Exception object
Return type:string

Indices and tables