From: Michael Orlitzky Date: Thu, 6 Oct 2016 18:04:43 +0000 (-0400) Subject: Add a few docs/examples to errors.py. X-Git-Tag: 0.1.0~200 X-Git-Url: https://gitweb.michael.orlitzky.com/?a=commitdiff_plain;h=4849db71b289f77851cc9bd98fc1fb7d1e41a811;p=dunshire.git Add a few docs/examples to errors.py. --- diff --git a/src/dunshire/errors.py b/src/dunshire/errors.py index bb52cac..3a5b601 100644 --- a/src/dunshire/errors.py +++ b/src/dunshire/errors.py @@ -5,23 +5,34 @@ Errors that can occur when solving a linear game. from cvxopt import matrix -def _pretty_print_dict(dictionary): +def _pretty_format_dict(dictionary): """ - Return a pretty-printed string representation of a dictionary + Return a pretty-formatted string representation of a dictionary containing CVXOPT matrices. + + EXAMPLES: + + >>> d = {'foo': 1.234, 'bar': matrix([1,2,3])} + >>> print(_pretty_format_dict(d)) + bar: + [ 1] + [ 2] + [ 3] + foo: 1.234 + """ result = '' for (key, value) in dictionary.items(): if isinstance(value, matrix): # Display matrices on their own lines, indented. - result += ' {:s}:'.format(key) + result += '{:s}:'.format(key) colvec = '\n{!s}'.format(value) - result += '\n '.join(colvec.splitlines()) + result += '\n '.join(colvec.splitlines()) result += '\n' else: - result += ' {:s}: {!s}\n'.format(key, value) + result += '{:s}: {!s}\n'.format(key, value) - return result + return result.rstrip('\n') # Kills trailing newlines on matrices. class GameUnsolvableException(Exception): @@ -46,7 +57,16 @@ class GameUnsolvableException(Exception): def __str__(self): + """ + Return a string representation of this exception. + + The returned representation highlights the "status" field of the + CVXOPT dictionary, since that should explain what went + wrong. The full CVXOPT solution dictionary is included after the + status. + """ tpl = 'Solution failed with result "{:s}."\n' \ - 'CVXOPT returned:\n{!s}' - return tpl.format(self._solution_dict['status'], - _pretty_print_dict(self._solution_dict)) + 'CVXOPT returned:\n {!s}' + cvx_lines = _pretty_format_dict(self._solution_dict).splitlines() + cvx_str = '\n '.join(cvx_lines) # Indent the whole dict by two spaces. + return tpl.format(self._solution_dict['status'], cvx_str)