peltak.core.util

class peltak.core.util.Singleton(*args, **kw)[source]

Base class for singletons.

Inheriting from this class will make your class a singleton. It should have an initializer that takes no arguments.

class peltak.core.util.cached_result[source]

Decorator that caches the function result.

This is especially useful for functions whose output won’t change during a single peltak execution run and are expensive (i.e. call external shell commands).

Example

>>> from peltak.core import util
>>>
>>> @util.cached_result()
... def foo():
...     call_count = getattr(foo, 'call_count', 0)
...     call_count += 1
...     setattr(foo, 'call_count', call_count)
>>> foo()
>>> print(foo.call_count)
1
>>> foo()
>>> print(foo.call_count)
1
>>> util.cached_result.clear(foo)
>>> foo()
>>> print(foo.call_count)
2
classmethod clear(fn)[source]

Clear result cache on the given function.

If the function has no cached result, this call will do nothing.

Parameters

fn (FunctionType) – The function whose cache should be cleared.

peltak.core.util.dict_has(dct, path)[source]

Check if a given dict has a value under a comma separated name/path.

This will split path by dots and drill down the dictionary to check if the value exists.

Return type

bool

peltak.core.util.get_from_dict(dct, path, *default)[source]

Get value from dictionary using a dotted path.

This allows you to get a value from deep within a dictionary without having to manually check at each level if the key exists and handling the default properly. This function will work the same as dict.get() but allows you to specify a path in dotted notation, eg: ‘main.sub.value’. Depending on whether you passed a default value it will either return it or raise KeyError if any of the keys or value itself is missing.

Parameters
  • dct (Dict) – The dict the requested value will be read from.

  • path (str) – The name/path of the config value.

  • *default – If given and the key doesn’t not exist, this will be returned instead. If it’s not given and the config value does not exist, KeyError will be raised.

Return type

Any

Returns

The requested config value. This is one of the global values defined in this file. If the value does not exist it will return default if give or raise AttributeError.

Raises

KeyError – If the value does not exist and default was not given.

Examples

>>> d = {
...     'main': {
...         'value': 123,
...     }
... }
...
>>> get_from_dict(d, 'main.value')
123
>>> get_from_dict(d, 'missing', 321)
321
>>> get_from_dict(d, 'missing')
Traceback (most recent call last):
KeyError:
peltak.core.util.in_batches(iterable, batch_size)[source]

Split the given iterable into batches.

Parameters
  • iterable (Iterable[Any]) – The iterable you want to split into batches.

  • batch_size (int) – The size of each bach. The last batch will be probably smaller (if the number of elements cannot be equally divided.

Returns

Will yield all items in batches of batch_size

size.

Return type

Iterator[list[Any]]

Example

>>> from peltak.core import util
>>>
>>> batches = util.in_batches([1, 2, 3, 4, 5, 6, 7], 3)
>>> batches = list(batches)     # so we can query for length
>>> len(batches)
3
>>> batches
[[1, 2, 3], [4, 5, 6], [7]]
peltak.core.util.mark_deprecated(replaced_by)[source]

Mark command as deprecated.

Parameters

replaced_by (str) – The command that deprecated this command and should be used instead.

Return type

Callable[[Callable[..., Any]], Callable[..., Any]]

peltak.core.util.mark_experimental(fn)[source]

Mark function as experimental.

Parameters

fn (FunctionType) – The command function to decorate.

Return type

Callable[..., Any]

peltak.core.util.remove_indent(text)[source]

Remove indentation from the text.

All indentation will be removed no matter if it’s consistent across the text.

Parameters

text (str) – The text that contains indentation.

Returns

The same text but with all indentation removed from each line.

Return type

str

peltak.core.util.set_in_dict(dct, path, value)[source]

Set value in a dictionary using a dotted path.

This is the opposite to get_from_dict() function, but sets the value under the given path instead.

Parameters
  • dct (Dict) – The dict that will be modified by this call.

  • path (str) – The name/path of the context value to change.

  • value (Any) – The new value for the selected context value

Raises

KeyError – If the value does not exist and default was not given.

Examples

>>> d = {
...     'main': {
...         'value': 123,
...     }
... }
...
>>> set_in_dict(d, 'main.value', 321)
>>> d
{'main': {'value': 321}}
Return type

None

class peltak.core.util.timed_block[source]

Context manager to measure execution time for a give block of code.

Example

>>> import time
>>> from peltak.core import util
>>>
>>> with util.timed_block() as t:
...     time.sleep(1)
>>>
>>> print("Code executed in {}s".format(int(t.elapsed_s)))
Code executed in 1s
t0

The time at the start of execution.

Type

float

elapsed

Raw elapsed time in seconds.

Type

float

elapsed_s

Elapsed time in seconds, rounded to 3 decimal places for easy display.

Type

float

elapsed_ms

Elapsed time in milliseconds, rounded to 3 decimal places for easy display.

Type

float

peltak.core.util.toml_dump(data, path_or_fp=None)[source]

Save a plain dict as a TOML file.

peltak.core.util.toml_load(path_or_fp)[source]

Load TOML configuration into a dict.

Return type

Dict[str, Any]

peltak.core.util.yaml_dump(data, stream=None)[source]

Dump data to a YAML string/file.

Parameters
  • data (YamlData) – The data to serialize as YAML.

  • stream (TextIO) – The file-like object to save to. If given, this function will write the resulting YAML to that stream.

Returns

The YAML string.

Return type

str

peltak.core.util.yaml_load(str_or_fp)[source]

Load data from YAML string or file-like object.

Parameters

str_or_fp (Union[str, TextIO]) –

Returns

The data loaded from the YAML string/file.

Return type

YamlData