Library reference

Core components

class py314.globals.SENTINEL

A Singleton Sentinel object.

py314.console.register_enumeration(cls)

A decorator for an enumeration cls that registers its members as global logging levels. The field name represents the logging level name and the field value is the logging level, hence is expected to be an integer.

Parameters:cls (enum.IntEnum) – Enumeration containing logging levels.
Returns:The decorated cls.
Return type:enum.IntEnum
class py314.console.SYS

System and internal logging enumeration.

ACTIVE
DEBUG
SQL
SUCCESS
PENDING
FAILURE
INFO
WARNING
ERROR
FATAL
AUTH

Auth daemon logging level.

TRACEBACK
SYSTEM

A generic logging level for system messages.

class py314.console.console

A generic console logger.

verbosity

int – Class attribute containing the logger verbosity.

debug_state

bool – Class attribute denoting whether the console is in debug mode or not.

frame_state

bool – Class attribute denoting whether the frame info is logged or not.

classmethod log(header, message, verbosity=0, fore=None, style=None)

For high enough verbosity, print in the terminal a message prefixed by a suitable header and decorated with ANSI color and style.

If header is a string, use a SYS.ACTIVE logging level.

Parameters:
classmethod traceback(message=None, *, raise_exc=False, depth=None)

Log the current frame F where this method is called. If an exception was raised and if message is None, then this exception is logged. Otherwise, log the message. The optional parameter depth denotes an ancestor frame, that is the first outer frame associated with F.

Parameters:
  • message (str [optional]) – The message to log.
  • raise_exc (bool [optional]) – Raise an artificial exception from None.
  • depth (int [optional]) – Ancestor frame depth to inspect.
classmethod append(message, fore=None, style=None)

Format message with the given arguments and align the log with the previous one if possible. This method must always follow another logging method, or else nothing will be logged. This method provides a multilines records support.

Parameters:
classmethod debug(message)

If the debug mode is enabled, log message with a debug style.

Parameters:message (str) – Message to log.
classmethod info(message, verbosity=1, style=None)

Log a message with a SYS.INFO logging level.

Parameters:
classmethod pending(message, verbosity=1)

Log a message with a SYS.PENDING logging level.

Parameters:
  • message (str) – The message to log.
  • verbosity (int [optional]) – Runtime verbosity.
classmethod success(message, verbosity=1)

Log a message with a SYS.PENDING logging level.

Parameters:
  • message (str) – The message to log.
  • verbosity (int [optional]) – Runtime verbosity.
classmethod warning(message)

Log a message with a SYS.WARNING logging level.

Parameters:message (str) – The message to log.
classmethod failure(message)

Log a message with a SYS.FAILURE logging level.

Parameters:message (str) – The message to log.
classmethod alert(level, message, fore='\x1b[31m')

Log a message with a level logging level.

Parameters:
  • level (SYS [optional]) – Logging level.
  • message (str) – The message to log.
classmethod fatal(message)

An alias for alert(SYS.FATAL, message).

See also

alert()

classmethod system(message)

An alias for alert(SYS.SYSTEM, message).

See also

alert()

classmethod sql(message, verbosity=0)

Log a message with a SYS.SQL logging level. The console must be enable its debug mode to log this message.

Parameters:
  • message (str) – The message to log.
  • verbosity (int [optional]) – Runtime verbosity.
classmethod set_verbosity(verbosity)

Define the minimum verbosity for enabling logging support.

classmethod set_debug(state)

Enable or disable the console debug mode.

classmethod observe(owner)

Add an object to benchmark.

Parameters:owner (WithTimeitPolicy) – Object to benchmark.
class py314.console.WithTimeitPolicy

Abstact interface for objects that are benchmarked.

classmethod enable_timeit_strategy()

Decorate some methods with WithTimeitPolicy.wraps().

classmethod disable_timeit_strategy()

Remove the timing decorators.

classmethod set_timeit_policy(flag)

Enable or disable the timeit strategy according to state.

classmethod wraps(callback, timeout=0, message=None)

Decorator for timing methods.

classmethod sqltimeit(callback, timeout)

SQL methods timing decorator.

Providers and disk

Configuration files

class py314.config.FileConfig(path)

A config object whose data is extracted from an YAML configuration file. It is possible to add a callback that takes no argument and which will be executed when the configuration has been updated at runtime.

Parameters:path (str) – The absolute path to the YAML file.
reload()

Reload the data from the configuration file and return if changes.

dumps()

Dump the configuration into the configuration file.

at(path, **kwargs)

Return the value of the leaf of the path in the configuration file.

walk(vectorized)

Check that the vectorized tree paths describe valid paths for self.

Parameters:vectorized (list) – A list of potential paths in self.

Disk utilitaries

This module provides extended functions to the os builtin module.

py314.disk.is_file_null(path)

Check either that path does not exist or is empty.

py314.disk.traverse(path, *, ordered=False)

Return a list of all paths in the directory tree of path.

py314.disk.base_filename(path)

Return the filname of path without its extension.

py314.disk.base_suffix(path)

Return the extension of path.

py314.disk.prefixed(path, *, prefix)

Check that path is not None and starts with prefix.

py314.disk.suffixed(path, *, suffix)

Check suffix is the suffix of path.

py314.disk.rmexpired(path, *, days=10)

Delete all files in the path folder older than days.

py314.disk.rmfiles(dirpath, *, skip_suffix=None, skip_prefix=None)

Delete all files in the dirpath folder not prefixed by skip_prefix and not suffixed by skip_suffix.

py314.disk.targzify(path)

Compress a path into a .tar.gz file with same file name.

Parameters:path (str) – Absolte file path denoting the file to compress.
py314.disk.create_files(dirpath, *filenames, suffix=None)

For each name in filenames, create a file named name inside a folder located at dirpath and of desired extension given by suffix.

Parameters:
  • dirpath (str) – Folder path.
  • *filenames – File names to create.
  • suffix (str [optional]) – Common file extension.
class py314.disk.FileContext(filename, mode='r', encoding=None, root='')

A file context manager for internal processing.

class py314.disk.DirectoryView(*paths)

A Directory view for a given root.

root

str – The joined path.

classmethod isfile(path)

Return True if path describes a file path.

classmethod isdir(path)

Return True if path describes a directory path.

class py314.disk.CompressManager(*paths, skip=None)

Compress all files located at path, except those in skip folder.

Parameters:paths (list) – A list of paths to join.
path

str – The compressed folder.

targzify(suffix, *, skip_prefix=None)

Compress all files in CompressManager.path ending with suffix but not starting with skip_prefix

Base Serializers

This module provides basic YAML and JSON serializers.

class py314.serializer.ABCSerializer

Abstract serializer.

classmethod load(stream)

Load the stream.

classmethod dump(raw, *args, **kwargs)

Dump the raw data.

Parameters:raw (object) – The raw data.
Returns:The raw data dumped with a format-specific function.
classmethod read(file, root=None, *, encoding='utf-8')

Load the file data.

Parameters:
  • file (str) – The file path rel to root.
  • root (str [optional]) – Base root path.
  • encoding (str [optional]) – File encoding. Defaults to ‘utf-8’.
Returns:

The raw data loaded with a format-specific loads function.

class py314.serializer.JSONSerializer

JSON Serializer based on the json.loads and the json.dumps functions.

load(*, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object.

object_hook is an optional function that will be called with the result of any object literal decode (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.

parse_float, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

parse_constant, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered.

To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used.

The encoding argument is ignored and deprecated.

dump(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj to a JSON formatted str.

If skipkeys is true then dict keys that are not basic types (str, int, float, bool, None) will be skipped instead of raising a TypeError.

If ensure_ascii is false, then the return value can contain non-ASCII characters if they appear in strings contained in obj. Otherwise, all such characters are escaped in JSON strings.

If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).

If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.

If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.

To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

class py314.serializer.YAMLSerializer

YAML Serializer based on the yaml.load and the yaml.dump functions.

load(Loader=<class 'yaml.loader.Loader'>)

Parse the first YAML document in a stream and produce the corresponding Python object.

dump(stream=None, Dumper=<class 'yaml.dumper.Dumper'>, **kwds)

Serialize a Python object into a YAML stream. If stream is None, return the produced string instead.

Theoretic sets

This module implements a theoretic set object and provides the four basic set operations, namely union, intersection, difference and symmetric diff. The builtin set class should be used whenever possible.

class py314.theory.TheoreticSet(iterable, tc=None)

A generic iterable class providing intersection, unions, difference and symmetric difference operations. If tc is given, then items are gathered into an iterable of type tc.

Parameters:
  • iterable (iterable) – An iterable containing the items.
  • tc (type [optional]) – Optional iterable class.

Volatile data

This module provides data containers with predefined lifespan.

class py314.volatile.Volatile(data, max_age)

Represent a data with a certain max_age.

Parameters:
  • data (object) – The underlying data.
  • max_age (int) – The object’s time duration.
  • parent (VolatileCache) – Container storing the volatile data (reference).
consume()

Consume prematuraly.

consumed

bool – Determine whether the data is marked as consumed or not.

data

object – Proxy to the current value.

class py314.volatile.VolatileCache

An associative array of volatile data.

entry(key)

Return the volatile data of key.

has(key)

Check that key is a valid volatile data key.

remove(key)

Delete the entry associated with key in the cache.

register(key, volatile)

Register a volatile with a specific key in the cache.

Parameters:
  • key (collections.Hashable) – A key for tracing back the volatile object.
  • volatile (Volatile) – A volatile object to insert in the cache.
consume(key)

Consume the entry in the cache associated with key. Silent exceptions arising from invalid keys.

clear()

Consume every items in the cache if possible and clear the cache.

class py314.volatile.VolatileCacheMapping(*cache_names)

An assocative array name → cache, where name is a str for an associative cache name and cache is an VolatileCache instance.

get_cache(cache_name, default=None)

Return the VolatileCache associated with cache_name.

register(cache_name, key, volatile)

Insert volatile into the VolatileCache named cache_name. If the latter does not exist, create it before the insertion.

Parameters:
  • cache_name (str) – A cache name.
  • key (collections.Hashable) – A key for tracing back the volatile object.
  • volatile (Volatile) – A volatile object to insert in the cache.
has_key(key)

Check that key belongs to a cache.

cache_of(key)

Return the first VolatileCache of key or None.

Fonctions and callbacks

class py314.adapter.Adapter(*, transformation=None)

A decorator that convert the output of a function to another type before returning it, without modifying the function itself.

Parameters:func (callable [optional]) – The transformation callable.
class py314.callback.Callback(callback=None)

Implement a strategy which executes a callback and does not care about the messenger.

Parameters:callback (callable [optional]) – The callback to execute.
__call__(messenger)

Call self as a function.

class py314.callback.Function(_=None, *args, **kwargs)

Represent a routine or a coroutine with bound values or not. Positional and keyword arguments pass to the _ whe invoked and extra arguments can be given at this time. Extra positional arguments are inserted after existing.

Parameters:_ (callable [optional]) – A callback to execute.
classmethod wraps(func, *args, **kwargs)

Wrap func inside a Function if it is not already the case and attach the positional and keyword arguments if needed.

execute(*args, **kwargs)

Pass positional and keyword arguments to the callback and ensure a synchronous execution of the latter.

fast_execute(*args, **kwargs)

Equivalent to execute() with no safe-execution check.

coroutine async_execute(*args, **kwargs)

Pass positional and keyword arguments to the callback and ensure an asychronous execution of the latter.

coroutine fast_async_execute(*args, **kwargs)

Equivalent to async_execute() with no safe-execution check.

class py314.callback.ChainMap(missing=None, sloppy=True)

A mapping whose keys are strings and values are chained callback. Define a callback to execute when a key is missing via the missing parameter.

Parameters:
  • missing (callable or Function [optional]) – Callback to execute when a key is not handled.
  • sloppy (bool [optional]) – Keys are handled case insensitively.
register(key, callback, *args, **kwargs)

Put a new Callback into the current chain of callbacks.

Parameters:
  • key (str) – The triggering key.
  • callback (callable) – The callback function to execute for this key.
remove(key)

Remove the tasks triggered by key.

Parameters:key (str) – The triggering key to remove.
on_missing(*args, **kwargs)

Called when a key is invalid.

class py314.callback.Switch(missing=None, **arrows)

Store callbacks and associate them with some keys.

The missing parameter describes a callback executed when a key string is not handled by the switch. If the callback requires parameters, it suffices to wrap it inside a Function instance.

Parameters:missing (callable or Function [optional]) – A callback to execute on invalid keys.
handles(key)

Check that key is handled by the switch.

register(key, callback, *args, **kwargs)

Add a callback for a specific key.

execute(key, *args, **kwargs)

Pass positional and keyword arguments to the callback attached to key or execute the on_missing callback if there is none.

coroutine async_execute(key, *args, **kwargs)

Pass positional and keyword arguments to the callback attached to key or asynchronously execute the on_missing callback if there is none.

class py314.callback.Promise(timeout, callback, *args, **kwargs)

Represent a scheduled task with callback (coroutine or not). The positional and keyword arguments are passed to callback.

Parameters:
  • timeout (Union[int, float]) – The timeout in seconds (usually strictly greater than 0).
  • callback (callable) – The callback to execute after the timer’s end.
running()

Return True if execute() has been called and the task is not cancelled.

__call__(*args, **kwargs)

Call self as a function.

execute()

Schedule the task and define its callback.

cancel()

Cancel the running task.

class py314.callback.EPromise(timeout, callback, *args, **kwargs)

A Promise running infinitely, restarting when finished.

py314.functions.this(x)

The identity map x → x.

py314.functions.const(obj)

A constant map x → obj.

py314.functions.functorize(maybe_func)

Return maybe_func if it is callable and this() otherwise.

py314.functions.aggregated(*, sentinel, n=None)

A predicate P(x) checking that x is not sentinel. If n is given, it is expected that x is an indexable iterable and P(x) checks that x[n] is not sentinel.

This module contains helper functions to check the arguments of a function. All functions raise an AssertionError if the assertion fails.

class py314.asserts.Assertions

Basic assertions.

classmethod assert_type(instance, *classinfo)

Assert that instance is of suitable type given by classinfo.

classmethod assert_unique(*args)

Assert that there is no duplicated arguments.

classmethod assert_values(**kwargs)

Assert that all values are true truth.

classmethod assert_has_attribute(func, name)

Assert that there is no func has an attribute field.

class py314.asserts.SilentAssertions

Empty assertions.

py314.inspect.get_f_kwargs(*, depth=1)

Return a tuple for frame formatting.

Decorators and descriptors

py314.enums.extend_flags(cls)

Decorator adding bitwise operations with types convertible to cls.

Parameters:cls (type) – A subclass of enum.Flag.

The following operators are implemented.

  • __and__(self, other) – Implement self % other
  • __or__(self, other) – Implement self | other.
  • __xor__(self, other) – Implement self ^ other.

The following operators use the above operators.

  • __ror__(self, other) – Implement other | self.
  • __rand__(self, other) – Implement other & self.
  • __rxor__(self, other) – Implement other ^ self.
py314.enums.as_field_name(cls)

Define a default __str__() method for enumerations.

Algorithms

Dictionary factory

This module contains a dict factory and algorithms dealing in general with dictionaries or two-dimensional iterables.

py314.collections.make_dict(iterable, *, key_adapter=None, val_adapter=None)

Make a dict defined by key_adapter(x) → val_adapter(x) as x ranges over iterable.

Parameter flat passes to functorize().

Parameters:
  • iterable (iterable) – A collection of items.
  • key_adapter (callable [optional]) – A key adapter.
  • val_adapter (callable [optional]) – A value adapter.
py314.collections.make_dict(mapping, *, key_adapter = None, val_adapter = None)

Overloads make_dict().

Make a dict defined by key_adapter(key) ↦ val_adapter(value) as (key, value) ranges over mapping.items().

Parameters:
  • mapping (dict) – A dictionary.
  • key_adapter (callable [optional]) – A key adapter.
  • val_adapter (callable [optional]) – A value adapter.
py314.collections.dict_from_keys(value, *keys)

Make a dict defined by key → deepcopy(value) as key ranges over keys.

py314.collections.alternate(mapping, *keys)

Make a tuple alternating key and mapping[key] from mapping as key ranges over keys.

py314.collections.attributes(obj, *attrs)

Make a dict defined by key → getattr(obj, key) as key ranges over attrs. Exceptions are propagated.

py314.collections.subdict(data, keys, key_adapter=None, val_adapter=None)

Make a dict defined by key_adapter(key) → val_adapter(data[key]) as key ranges over keys and where keys is a subset of data.keys().

Parameters:
  • data (dict) – Original dictionary.
  • keys (iterable) – A list of keys in data.
  • key_adapter (callable [optional]) – A key adapter.
  • val_adapter (callable [optional]) – A value adapter.

Iteration

This module contains algorithms to flatten and iterate over iterables.

py314.iteration.next_iter(iterable, default=None)

Return the next iterator value or default if nothing can be fetched.

py314.iteration.starif(iterable, classinfo)

Return tuple(iterable) if iterable is an instance of a class or of a subclass thereof; otherwise, return a 1-uplet consisting of iterable.

Parameters:
  • iterable (iterable) – Iterable to transform.
  • classinfo (Union[type, Tuple[type]]) – Tuple of types.
py314.iteration.flatten(*args)

Recursively flatten each tuple in args and make an one-dimensional tuple with no tuples in it.

Nested tuples are not flattened., that is (x, (y)) and (x, [y]) will yield (x, y) and (x, [y]) respectively.

py314.iteration.unpack(iterable, classinfo)

Deeply flatten items in iterable whose type is given in classinfo.

Parameters:
  • iterable (iterable) – Iterable to transform.
  • classinfo (Union[type, Tuple[type]]) – Tuple of types.
py314.iteration.is_next(iterable, classinfo=(<class 'list'>, <class 'tuple'>))

Check that iterable is an instance of a class or of a subclass thereof as well as it is of length 1. In other words, check that iterable is a set in the mathematical sense that is in bijection with its elements.

Parameters:
  • iterable (iterable) – Iterable to transform.
  • classinfo (Union[type, Tuple[type]] [optional]) – Tuple of types.
py314.iteration.self_next(iterable, classinfo=(<class 'list'>, <class 'tuple'>))

Check that iterable satisfies is_next() and remove the set delimiters of iterable by returning its value. Otherwise, do nothing.

Parameters:
  • iterable (iterable) – Iterable to transform.
  • classinfo (Union[type, Tuple[type]] [optional]) – Tuple of types.
py314.iteration.take_next(iterable, classinfo=(<class 'list'>, ))

Return the first element iterable[0] of an iterable that is an instance of a class or of a subclass thereof; otherwise, return iterable.

Parameters:
  • iterable (iterable) – Iterable to transform.
  • classinfo (Union[type, Tuple[type]] [optional]) – Tuple of types.
Raise:

IndexError – Empty iterable.

py314.iteration.take_first_leaf(iterable, classinfo=(<class 'list'>, ))

Equivalent to take_first_leaf(take_next(iterable, classinfo), classinfo). If iterable is empty or is None, stop the recursion.

Parameters:
  • iterable (iterable) – Iterable to transform.
  • classinfo (Union[type, Tuple[type]] [optional]) – Tuple of types.

Iterators

This module contains algorithms dealing with iterators and generators.

py314.iterators.zipsafe(*iterables)

Make an zip iterator aggregating items from each of the iterables. The iterator is an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

With a single iterable argument, return the iterable itself and with no arguments, return an empty tuple.

Raise:ValueError – No iterables are given.
Raise:IndexError – Iterables have not same size.
py314.iterators.side_effect(func, iterable, *, nargs=1)

Make a tuple aggregating func(x(i,1), …, x(i,n)), for all 1 ≤ i ≤ len(iterable) and 1 ≤ n ≤ len(args) as args ranges over iterable or iterable.items().

To avoid calculations, it is possible to provide the number of arguments expected by func via nargs. By default, nargs is set to 1 and if it is None or 0, then func(*args) is called instead.

Parameters:
  • func (callable) – A function to apply on each item.
  • iterable (iterable) – The iterable to iterate through.
  • nargs (int [optional]) – The number of expected arguments from func (default: 1).
py314.iterators.consume(iterable)

Efficiently consume iterable without returning values.

Parameters:iterable (iterable) – A iterable to exhaust.

Search

This module contains search algorithms.

py314.search.partition(predicate, iterable, adapter=None)

Return a pair (yes, no),where yes and no are subsets of iterable over which predicate evaluates to True and False respectively. If adapter is given, return (adapter(yes), adapter(no)) instead.

Parameters:
  • predicate (callable) – A predicate to apply.
  • iterable (iterable) – The iterable to partition.
  • adapter (callable [optional]) – An adapter to apply on the yes and no subsets.
py314.search.locate(predicate, iterable)

A helper to return a list of the indices / keys of the items of iterable that meet the predicate.

Parameters:
  • predicate (callable) – A predicate to apply.
  • iterable (iterable) – The iterable to search through.
py314.search.position(predicate, iterable)

A helper to return the first index or the key of an element of iterable that meets the predicate. If no index can be retrieved, return None.

Parameters:
  • predicate (callable) – A predicate to apply.
  • iterable (iterable) – The iterable to search through.
py314.search.find(predicate, iterable, default=None)

A helper to return the first element found in the sequence iterable that meets the predicate.

Parameters:
  • predicate (callable) – A predicate to apply.
  • iterable (iterable) – The data to search through.
  • default (object [optional]) – An object to return in case of search failure.
Returns:

The first item that meets the predicate or default.

Examples

user = find(lambda u: u.id == 1, user_list)

would find the user in the user’s list whose id (assuming that this attribute exists) and returns it.

Note

This is different from filter due to the fact it stops the moment it finds a valid entry.

py314.search.occurrences(predicate, iterable)

Count the number of items in iterable satisfying predicate.

Parameters:
  • predicate (callable) – A predicate to apply.
  • iterable (iterable) – The data to range over.

Decomposition

py314.splits.take_n(iterable, n, *, adapter=None)

Return the first n items of the iterable as a tuple.

Parameters:adapter (callable [optional]) – An adapter to call on each item in iterable.
py314.splits.chunkize(iterable, size, *, adapter=None)

Make a generator whose elements are tuple of cardinality size of an iterable iterable supporting elements access via index.

Parameters:
  • iterable (Union[list, tuple]) – The iterable to partition.
  • size (int) – The size of the chunks.
  • adapter (callable [optional]) – An adapter to call on each item in iterable.
py314.splits.chunkize(mapping, size)

Overloads chunkize().

Slice a mapping into chunks of length size. No order is guaranteed if there is no possible one.

Parameters:
  • mapping (dict) – The collection to slice.
  • size (int) – The number of items per chunk.
py314.splits.evenize(data)

Split data into its maximal subset of even size and the rest.

py314.splits.to_slice(x, limit)

Return a slice depending on x. If x is None, return (0, limit).

Parameters:
  • x (object) – An index, a slice or None.
  • limit (int) – The stop descriptor of slice.

Tree

This module implements a graph theoretic approach for dict.

py314.tree.reach(tree, path, *, check=False, adapter=None, default=<class 'py314.globals.SENTINEL'>)

Navigate in tree via path and return the end node, adapted if needed.

Parameters:
  • tree (Mapping) – The tree to consider.
  • path (str) – A sequence of nested keys of the form k1/k2/k3 ….
  • check (bool [optional]) – Check that path is a valid path in tree.
  • adapter (callable [optional]) – End-node adapter on non-default value and no error.
  • default (object [optional]) – Value to return if the end node cannot be reached.
Raises:

KeyError – Invalid path and no default given.

py314.tree.set_leaf(tree, path, value, *, check=False)

Modify the end node of path in a nested directory tree.

Parameters:
  • tree (dict) – The tree to modify.
  • path (str) – A sequence of nested keys of the form k1/k2/k3 ….
  • value (object) – The new leaf value.
  • check (bool [optional]) – Check that path is a valid path in tree.
Raises:

KeyError – Checking path failed.

py314.tree.vectorize(tree)

Given tree, return all possible paths in a /-nested format.

Parameters:tree (dict) – A dictionary.

Miscellaneous

py314.process.reboot()

Restart the program, with file objects and descriptors cleanup.

py314.process.die()

Kill the program.

class py314.requests.HTTPMethod

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred to as HTTP verbs.

Each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request method can be safe, idempotent, or cacheable.

GET

Retrieve a representation of the specified resource.

HEAD

Ask for a response identical to that of a GET request, but without the response body.

POST

Submit an entity to the specified resource, often causing a change in state or side effects on the server.

PUT

Replace all current representations of the target resource with the request payload.

DELETE

Delete the specified resource.

CONNECT

Establish a tunnel to the server identified by the target resource.

OPTIONS

Describe the communication options for the target resource.

TRACE

Perform a message loop-back test along the path to the target resource.

PATCH

Apply partial modifications to a resource.

coroutine py314.requests.request(meth, url, *, timeout=300, headers=None, params=None)

Execute an HTTP meth request given by url.

Parameters:
  • meth (HTTPMethod) – HTTP Method.
  • url (str) – Request URL.
  • timeout (float [optional]) – Timeout in milliseconds.
  • headers (dict [optional]) – Request headers.
  • params (dict [optional]) – Request parameters.
class py314.requests.ABCAPIClient

API Client meta class.

coroutine get(url, **kwargs)

Execute a HTTPMethod.GET request via request().

Parameters:url (str) – Request URL.
coroutine post(url, **kwargs)

Execute a HTTPMethod.POST request via request().

Parameters:url (str) – Request URL.
coroutine request(method, url, **kwargs)

Reimplement request() behaviour.

classmethod gather_error(error)

Analyze a possible error and raise an exception on error.

py314.time.deltatime(*, start=datetime.datetime(1970, 1, 1, 0, 0), stop=None, ms=False)

Compute the seconds (with microseconds part) between start and stop.

Parameters:
  • start (datetime.datetime [optional]) – A starting time point.
  • stop (datetime.datetime [optional]) – An ending time point (if None, set to now).
  • ms (bool [optional]) – Conversion into milliseconds.
class py314.unicode.Unicode

Traits class for unicode characters.

classmethod backward()

Unicode character for :arrow_backward:.

classmethod fast_backward()

Unicode character for :track_previous:.

classmethod forward()

Unicode character for :arrow_forward:.

classmethod fast_forward()

Unicode character for :track_forward:.

classmethod eject()

Unicode character for :thumbsdown:.

classmethod cross()

Unicode character for :cross:.

classmethod check()

Unicode character for :cross:.

classmethod bullet()

Unicode character for a black bullet.

classmethod invsep()

Unicode character for soft invsep. Useful for specifying a space that is not consumed by inline markdown.

classmethod electric_arrow()

Unicode character for a electric arrow.

classmethod high_voltage()

Unicode character for a high voltage sign.

classmethod square_lozenge()

Unicode character for a squared lozange.

classmethod hourglass()

Unicode character for a hourglass with flowing sand.

classmethod warning_sign()

Unicode character for a warning sign.

classmethod thumbsup()

Unicode character for :thumbsup:.

classmethod thumbsdown()

Unicode character for :thumbsdown:.

classmethod info()

Unicode character for info.

classmethod bell()

Unicode character for :bell:.

International System and Unit conversion

This module contains basic functions and pre-implemented classes for units conversion.

class py314.unit.Unit

Base class for a unit object.

standard

StandardUnit – A reference to the standard unit attached to this unit.

name

str – The unit’s abbreviation name.

factor

float – The multiplicator factor used by to_std().

standardize

callable – A function which takes a unique parameter, the value, and transforms it into its representation in the International System. SharedSpecs to a multiplication by Unit.factor.

reverse

callable – A function which takes a unique parameter, the representation in the international system (IS) of a value, and transforms it into its representation in the current Unit. SharedSpecs to a division by Unit.factor.

classmethod to_std(value, *, prec=None)

Assuming the value’s unit is the same as a children subclass of Unit, convert this value into its standard form (IS), via Unit.factor or Unit.standardize().

Parameters:
  • value – The value to convert.
  • prec (int [optional]) – Maximum amount of digits.
Returns:

The desired conversion or None for a non-conversion.

classmethod from_std(value, *, prec=None)

Assuming the value’s unit is the same as Unit.standard, convert value into its representation as a Unit via Unit.factor or Unit.reverse().

Parameters:
  • value – The value to convert.
  • prec (int [optional]) – Maximum amount of digits.
Returns:

The desired conversion or None for a non-conversion.

class py314.unit.StandardUnit

Standard unit from International Unit System.

standard

alias of StandardUnit

class py314.unit.Quantity(unit, value, adapter=None)

Base class for a value of any form.

Parameters:
  • unit (Unit) – The base unit class.
  • value (float) – The value in the given unit format.
  • adapter (callable [optional]) – Adapter transforming floating point values.
print(*, prec=None)

Print the current value with a certain precision.

Parameters:prec (int [optional]) – Maximum amount of digits.
std(*, prec=None)

Return the current value in a standard form.

Parameters:prec (int [optional]) – Maximum amount of digits.
convert(target_unit, *, prec=None)

Convert the current value into the given target_unit.

Parameters:
  • target_unit (Unit) – The unit the value is going to be converted into.
  • prec (int [optional]) – Maximum amount of digits for the final result and not during the process of conversion to IS.
class py314.unit.Time

Namespace for time quantities.

class SECOND
standard

alias of Time.SECOND

class NANOSECOND
standard

alias of Time.SECOND

class MICROSECOND
standard

alias of Time.SECOND

class MILLISECOND
standard

alias of Time.SECOND

class MINUTE
standard

alias of Time.SECOND

class HOUR
standard

alias of Time.SECOND

class DAY
standard

alias of Time.SECOND

class py314.unit.Temperature

Namespace for temperature quantities.

class KELVIN
standard

alias of Temperature.KELVIN

class CELSIUS
standard

alias of Temperature.KELVIN

class py314.unit.Speed

Namespace for speed quantities.

class MPS
standard

alias of Speed.MPS

class KPS
standard

alias of Speed.MPS

class KMPH
standard

alias of Speed.MPS

class py314.unit.Distance

Namespace for distance quantities.

class METER
standard

alias of Distance.METER

class NANOMETER
standard

alias of Distance.METER

class MICROMETER
standard

alias of Distance.METER

class KILOMETER
standard

alias of Distance.METER

class LIGHTYEAR
standard

alias of Distance.METER

Vendor

This module generates ANSI character codes to printing colors to terminals.

class py314.vendor.pydec.AnsiCodes

The subclasses declare class attributes which are numbers.

Upon instantiation we define instance attributes, which are the same as the class attributes but wrapped with the ANSI escape sequence.

class py314.vendor.pydec.AnsiFore

ANSI Codes for BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN and WHITE colors, and a RESET code. Extended support contains the light versions of the above colors but this is non-standard.

class py314.vendor.pydec.AnsiStyle

ANSI Codes for BRIGHT, DIM, ITSHAPE, UNDERLINED, STRIKED text decorations. A NORMAL and a RESET_ALL decoration is also available.

Google Text-To-Speech API

Provide an interface to deal with Google Text-To-Speech API.

class py314.vendor.tts.gTTS(text, lang=None, slow=False, debug=False)

An interface to Google’s Text to Speech API (gTTS).

save(savefile)

Do the Web request and save to savefile.

raw()

Return binary raw data.

write_to_fp(fp)

Do the Web request and save to a file-like object.