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