dipas.utils module

General purpose utility functions.

class dipas.utils.PatternDict

Bases: object

A dictionary with re.Pattern instances as keys. Item lookup is performed by matching against these patterns.

In addition to re.Pattern, also str objects are allowed as keys when setting an item. These are converted internally. If such a str object contains a * it is interpreted as a wildcard and it gets converted to the regex equivalent: .*?. For item lookup, only str objects are allowed since they get matched against the patterns. The first matching pattern’s corresponding value will be returned.

clear()

Remove all patterns and corresponding values.

class dipas.utils.TemporaryFileName(f_name: str = 'tempfile')

Bases: TemporaryDirectory

Create a temporary file name for read and write access inside a temporary directory for portability.

dipas.utils.autodoc(source, *, override: bool = False)

Automatically fill in missing docstrings from the provided source object.

dipas.utils.copy_doc(source, *, override: bool = False)

Copy the docstring of one object to another.

dipas.utils.flatten_nested_lists(nested: List) List

Flatten the given nested instances of lists.

Parameters

nested (list) – A list possibly containing other lists.

Returns

flat – A flat version of the given nested lists.

Return type

list

Examples

>>> flatten_nested_lists([1, 2, 3])
[1, 2, 3]
>>> flatten_nested_lists([1, [2, [3]]])
[1, 2, 3]
>>> flatten_nested_lists([1, 2, [3, [4, 5], 6], 7, 8])
[1, 2, 3, 4, 5, 6, 7, 8]
dipas.utils.format_doc(**kwargs)

Format the doc string of an object according to str.format rules.

dipas.utils.func_chain(*funcs)

Return a partial object that, when called with an argument, will apply the given functions in order, using the output of the previous function as an input for the next (starting with the argument as the initial value).

dipas.utils.get_type_hints_with_boundary(obj, globalns=None, localns=None, boundary=None)

Like typing.get_type_hints for a class but allows to specify an upper boundary for the MRO.

dipas.utils.numpy_compatible(func)

Decorator which converts positional arguments from Numpy arrays to backend tensors and vice versa for the return value.

dipas.utils.pad_max_shape(*arrays, before=None, after=1, value=0, tie_break=<MagicMock name='mock.floor' id='139745954736976'>) ndarray' id='139745953275856'>]

Pad the given arrays with a constant values such that their new shapes fit the biggest array.

Parameters
  • arrays (sequence of arrays of the same rank) –

  • before ({float, sequence, array_like}) – Similar to np.pad -> pad_width but specifies the fraction of values to be padded before and after respectively for each of the arrays. Must be between 0 and 1. If before is given then after is ignored.

  • after ({float, sequence, array_like}) – Similar to np.pad -> pad_width but specifies the fraction of values to be padded before and after respectively for each of the arrays. Must be between 0 and 1. If before is given then after is ignored.

  • value (scalar) – The pad value.

  • tie_break (ufunc) – The actual number of items to be padded _before_ is computed as the total number of elements to be padded times the before fraction and the actual number of items to be padded _after_ is the remainder. This function determines how the fractional part of the before pad width is treated. The actual before pad with is computed as tie_break(N * before).astype(int) where N is the total pad width. By default tie_break just takes the np.floor (i.e. attributing the fraction part to the after pad width). The after pad width is computed as total_pad_width - before_pad_width.

Returns

padded_arrays

Return type

list of arrays

dipas.utils.remove_duplicates(seq: ~typing.Sequence, op=<built-in function eq>) List

Remove duplicates from the given sequence according to the given operator.

Examples

>>> import operator as op
>>> remove_duplicates([1, 2, 3, 1, 2, 4, 1, 2, 5])
[1, 2, 3, 4, 5]
>>> from dataclasses import dataclass
>>> @dataclass
... class Foo:
...     n: int
...
>>> a, b, c = Foo(1), Foo(2), Foo(1)
>>> remove_duplicates([c, b, b, c, a, b, a])
[Foo(n=1), Foo(n=2)]
>>> remove_duplicates([c, b, b, c, a, b, a], op=op.is_)
[Foo(n=1), Foo(n=2), Foo(n=1)]
dipas.utils.safe_math_eval(expr: str, locals_dict: Optional[dict] = None) Any

Safe evaluation of mathematical expressions with name resolution.

The input string is converted to lowercase and any whitespace is removed. The expression is evaluated according to Python’s evaluation rules (e.g. ** denotes exponentiation). Any names, again according to Python’s naming rules, are resolved via the locals_dict parameter.

Parameters
  • expr (str) – The mathematical expression to be evaluated.

  • locals_dict (dict) – Used for name resolution.

Return type

The value of the expression, in the context of names present in locals_dict.

Raises
  • TypeError – If expr is not a string.

  • ValueError – If the evaluation of expr is considered unsafe (see the source code for exact rules).

  • NameError – If a name cannot be resolved via locals_dict.

Examples

>>> safe_math_eval('2 * 3 ** 4')
162
>>> import math
>>> safe_math_eval('sqrt(2) * sin(pi/4)', {'sqrt': math.sqrt, 'sin': math.sin, 'pi': math.pi})
1.0
>>> safe_math_eval('2.0 * a + b', {'a': 2, 'b': 4.0})
8.0
dipas.utils.setattr_multi(obj, names: Sequence[str], values: Union[Sequence, Dict[str, Any]]) None

Set multiple attributes at once.

Parameters
  • obj (object) –

  • names (sequence) –

  • values (sequence or dict) – If dict then it must map names to values.

class dipas.utils.singledispatchmethod(func)

Bases: object

register(cls, method=None)