Source code for basic_utils.core

from functools import reduce
from itertools import chain
from operator import attrgetter
from os import name, system
from typing import Any, List, Sequence, Tuple

__all__ = [

[docs]def slurp(fname: str) -> str: """ Reads a file and all its contents, returns a single string """ with open(fname, 'r') as f: data = return data
[docs]def clear() -> None: """ Clears the terminal screen from python, operating system agnostic """ system('cls' if name == 'nt' else 'clear')
[docs]def to_string(objects: List[object], sep: str=", ") -> str: """ Converts a list of objects into a single string >>> to_string([1, 2, 3]) '1, 2, 3' """ return sep.join(map(str, objects))
[docs]def getattrs(obj: object, keys: Sequence[str]) -> Tuple[Any, ...]: """Supports getting multiple attributes from a model at once""" return tuple(getattr(obj, key) for key in keys)
[docs]def map_getattr(attr: str, object_seq: Sequence[object]) -> Tuple[Any, ...]: """ Returns a map to retrieve a single attribute from a sequence of objects """ return tuple(map(attrgetter(attr), object_seq))
[docs]def rgetattr(obj: object, attrs: str) -> Any: """Get a nested attribute within an object""" return reduce(getattr, chain([obj], attrs.split('.')))
[docs]def rsetattr(obj: object, attr: str, val: Any) -> None: """Sets a nested attribute within an object""" pre, _, post = attr.rpartition('.') return setattr(rgetattr(obj, pre) if pre else obj, post, val)