utils

General utility functions.

Changed in version 1.0.0:

Changed in version 2.3.0: Removed domdf_python_tools.utils.deprecated(). Use the new deprecation-alias package instead.

Data:

SPACE_PLACEHOLDER

The character.

etc

Object that provides an ellipsis string

pyversion

The current major python version.

Functions:

cmp(x, y)

Implementation of cmp for Python 3.

convert_indents(text[, tab_width, from_, to])

Convert indentation at the start of lines in text from tabs to spaces.

divide(string, sep)

Divide a string into two parts, about the given string.

double_repr_string(string)

Like repr(str), but tries to use double quotes instead.

enquote_value(value)

Adds single quotes (') to the given value, suitable for use in a templating system such as Jinja2.

head(obj[, n])

Returns the head of the given object.

list2str(the_list[, sep])

Convert an iterable, such as a list, to a comma separated string.

magnitude(x)

Returns the magnitude of the given value.

posargs2kwargs(args, posarg_names[, kwargs])

Convert the positional args in args to kwargs, based on the relative order of args and posarg_names.

printe(*values[, sep, end])

Alias of stderr_writer()

printr(obj, *values[, sep, end, file, flush])

Print the repr() of an object.

printt(obj, *values[, sep, end, file, flush])

Print the type of an object.

redirect_output([combine])

Context manager to redirect stdout and stderr to two io.StringIO objects.

redivide(string, pat)

Divide a string into two parts, splitting on the given regular expression.

replace_nonprinting(string[, exclude])

Replace nonprinting (control) characters in string with ^ and M- notation.

stderr_writer(*values[, sep, end])

Print *values to sys.stderr, separated by sep and followed by end.

str2tuple(input_string[, sep])

Convert a comma-separated string of integers into a tuple.

strtobool(val)

Convert a string representation of truth to True or False.

trim_precision(value[, precision])

Trim the precision of the given floating point value.

unique_sorted(elements, *[, key, reverse])

Returns an ordered list of unique items from elements.

SPACE_PLACEHOLDER = '␣'

Type:    str

The character.

cmp(x, y)[source]

Implementation of cmp for Python 3.

Compare the two objects x and y and return an integer according to the outcome.

The return value is negative if x < y, zero if x == y and strictly positive if x > y.

Return type

int

convert_indents(text, tab_width=4, from_='\t', to=' ')[source]

Convert indentation at the start of lines in text from tabs to spaces.

Parameters
  • text (str) – The text to convert indents in.

  • tab_width (int) – The number of spaces per tab. Default 4.

  • from_ (str) – The indent to convert from. Default '\t'.

  • to (str) – The indent to convert to. Default '␣'.

Return type

str

divide(string, sep)[source]

Divide a string into two parts, about the given string.

New in version 2.7.0.

Parameters
  • string (str)

  • sep (str) – The separator to split at.

Return type

Tuple[str, str]

double_repr_string(string)[source]

Like repr(str), but tries to use double quotes instead.

New in version 2.5.0.

Parameters

string (str)

Return type

str

enquote_value(value)[source]

Adds single quotes (') to the given value, suitable for use in a templating system such as Jinja2.

Floats, integers, booleans, None, and the strings 'True', 'False' and 'None' are returned as-is.

Parameters

value (Any) – The value to enquote

Return type

Union[str, bool, float]

etc = ...

Type:    _Etcetera

Object that provides an ellipsis string

New in version 0.8.0.

head(obj, n=10)[source]

Returns the head of the given object.

New in version 0.8.0.

Parameters

See also

Return type

Optional[str]

list2str(the_list, sep=',')[source]

Convert an iterable, such as a list, to a comma separated string.

Parameters
  • the_list (Iterable[Any]) – The iterable to convert to a string.

  • sep (str) – Separator to use for the string. Default ','.

Return type

str

Returns

Comma separated string

magnitude(x)[source]

Returns the magnitude of the given value.

  • For negative numbers the absolute magnitude is returned.

  • For decimal numbers below 1 the magnitude will be negative.

New in version 2.0.0.

Parameters

x (float) – Numerical value to find the magnitude of.

Return type

int

posargs2kwargs(args, posarg_names, kwargs=None)[source]

Convert the positional args in args to kwargs, based on the relative order of args and posarg_names.

Important

Python 3.8’s Positional-Only Parameters (PEP 570) are not supported.

New in version 0.4.10.

Parameters
  • args (Iterable[Any]) – List of positional arguments provided to a function.

  • posarg_names (Union[Iterable[str], Callable]) – Either a list of positional argument names for the function, or the function object.

  • kwargs (Optional[Dict[str, Any]]) – Optional mapping of keyword argument names to values. The arguments will be added to this dictionary if provided. Default {}.

Return type

Dict[str, Any]

Returns

Dictionary mapping argument names to values.

Changed in version 2.8.0: The “self” argument for bound methods is ignored. For unbound methods (which are just functions) the behaviour is unchanged.

printe(*values, sep=' ', end='\n')

Alias of stderr_writer()

printr(obj, *values, sep=' ', end='\n', file=None, flush=False)[source]

Print the repr() of an object.

If no objects are given, printr() will just write end.

Parameters
  • obj (Any)

  • *values (object) – Additional values to print. These are printed verbatim.

  • sep (Optional[str]) – The separator between values. Default '␣'.

  • end (Optional[str]) – The final value to print. Setting to '' will leave the insertion point at the end of the printed text. Default '\n'.

  • file (Optional[IO]) – The file to write to. If not present or None, sys.stdout will be used.

  • flush (bool) – If True the stream is forcibly flushed after printing. Default False.

printt(obj, *values, sep=' ', end='\n', file=None, flush=False)[source]

Print the type of an object.

If no objects are given, printt() will just write end.

Parameters
  • obj (Any)

  • *values (object) – Additional values to print. These are printed verbatim.

  • sep (Optional[str]) – The separator between values. Default '␣'.

  • end (Optional[str]) – The final value to print. Setting to '' will leave the insertion point at the end of the printed text. Default '\n'.

  • file (Optional[IO]) – The file to write to. If not present or None, sys.stdout will be used.

  • flush (bool) – If True the stream is forcibly flushed after printing. Default False.

pyversion = 3

Type:    int

The current major python version.

redirect_output(combine=False)[source]

Context manager to redirect stdout and stderr to two io.StringIO objects.

These are assigned (as a tuple) to the target the as expression.

Example:

with redirect_output() as (stdout, stderr):
    ...

New in version 2.6.0.

Parameters

combine (bool) – If True stderr is combined with stdout. Default False.

Return type

Iterator[Tuple[StringIO, StringIO]]

redivide(string, pat)[source]

Divide a string into two parts, splitting on the given regular expression.

New in version 2.7.0.

Parameters
Return type

Tuple[str, str]

replace_nonprinting(string, exclude=None)[source]

Replace nonprinting (control) characters in string with ^ and M- notation.

New in version 3.3.0.

Parameters
Return type

str

See also

C0 and C1 control codes on Wikipedia

stderr_writer(*values, sep=' ', end='\n')[source]

Print *values to sys.stderr, separated by sep and followed by end.

sys.stdout is flushed before printing, and sys.stderr is flushed afterwards.

If no objects are given, stderr_writer() will just write end.

Parameters
  • *values (object)

  • sep (Optional[str]) – The separator between values. Default '␣'.

  • end (Optional[str]) – The final value to print. Setting to '' will leave the insertion point at the end of the printed text. Default '\n'.

Changed in version 3.0.0: The only permitted keyword arguments are sep and end. Previous versions allowed other keywords arguments supported by print() but they had no effect.

str2tuple(input_string, sep=',')[source]

Convert a comma-separated string of integers into a tuple.

Important

The input string must represent a comma-separated series of integers.

Parameters
  • input_string (str) – The string to be converted into a tuple

  • sep (str) – The separator in the string. Default ','.

Return type

Tuple[int, …]

strtobool(val)[source]

Convert a string representation of truth to True or False.

If val is an integer then its boolean representation is returned. If val is a boolean it is returned as-is.

True values are 'y', 'yes', 't', 'true', 'on', '1', and 1.

False values are 'n', 'no', 'f', 'false', 'off', '0', and 0.

Parameters

val (Union[str, int])

Raises

ValueError if val is anything else.

Return type

bool

trim_precision(value, precision=4)[source]

Trim the precision of the given floating point value.

For example, if you have the value 170.10000000000002 but really only care about it being 179.1:

>>> trim_precision(170.10000000000002, 2)
170.1
>>> type(trim_precision(170.10000000000002, 2))
<class 'float'>

New in version 2.0.0.

Parameters
  • value (float)

  • precision (int) – The number of decimal places to leave in the output. Default 4.

Return type

float

unique_sorted(elements, *, key=None, reverse=False)[source]

Returns an ordered list of unique items from elements.

New in version 3.0.0.

Parameters
  • elements (Iterable)

  • key (Optional[Callable]) – A function of one argument used to extract a comparison key from each item when sorting. For example, key=str.lower. The default value is None, which will compare the elements directly. Default None.

  • reverse (bool) – If True the list elements are sorted as if each comparison were reversed. Default False.

See also

set and sorted()

Return type

List

Overloads