rics.utility package

Subpackages

Submodules

rics.utility.collections module

Miscellaneous utility methods for Python collections.

rics.utility.collections.reverse_dict(d: Dict[Hashable, Hashable], inplace: bool = False) Optional[Dict[Hashable, Hashable]][source]

Swap keys and values.

Parameters
  • d – A dict to reverse.

  • inplace – If True, perform the reversal inplace.

Returns

A reversed version of d, or None if inplace is True.

Examples

Reversing a dict with two elements.

>>> from rics.utility.collections import reverse_dict
>>> reverse_dict({"A": 0, "B": 1})
{0: 'A', 1: 'B'}
rics.utility.collections.flatten_dict(d: Dict[str, Any], join_string: str = '.', filter_predicate: Optional[Callable[[str, Any], bool]] = None) Dict[str, Any][source]

Flatten a nested dictionary.

Parameters
  • d – A dict to flatten.

  • join_string – Joiner for nested keys.

  • filter_predicate – A callable which takes a key and value, returning True if the entry should be kept.

Returns

A flattened version of d.

Examples

Flattening a shallow nested dict.

>>> from rics.utility.collections import flatten_dict
>>> flatten_dict({"foo": 0, "bar": {"foo": 1, "bar": 2}})
{'foo': 0, 'bar.foo': 1, 'bar.bar': 2}

rics.utility.logs module

A namespace for logging constants, and a wrapper rics.utility.logs.basic_config() for the standard logging.basicConfig()-method with defaults which are defined here.

rics.utility.logs.FORMAT: str = '%(asctime)s.%(msecs)03d [%(name)s:%(levelname)s] %(message)s'

Default logging format; logging.basicConfig(format=FORMAT)

Sample: <date-format>.378 [rics:DEBUG] I'm a debug message!

rics.utility.logs.DATE_FORMAT: str = '%Y-%m-%dT%H:%M:%S'

Default logging date format; logging.basicConfig(datefmt=DATE_FORMAT)

Sample: 2022-02-05T11:17:05<logging-format>

rics.utility.logs.basic_config(rics_level: Optional[Union[int, str]] = None, force: bool = True, **kwargs: Any) None[source]

Do basic logging configuration with package defaults.

Parameters
  • rics_level – Log level for the rics package. None=inherit.

  • force – If True, override existing configuration if it exists.

  • **kwargs – Keyword arguments for logging.basicConfig().

Keyword Arguments

<namespace>_level – Log level for the namespace denoted by namespace (without the “_level”-suffix). Use underscores instead of dots for submodules, eg module.submodule => module_submodule.

rics.utility.misc module

Miscellaneous utility methods for Python applications.

rics.utility.misc.tname(arg: Optional[Union[Type[Any], Any, Callable]]) str[source]

Get name of method or class.

Parameters

arg – Something get a name for.

Returns

A type name.

rics.utility.misc.get_local_or_remote(file: Union[str, bytes, PathLike], remote_root: Union[str, bytes, PathLike], local_root: Union[str, bytes, PathLike] = '.', force: bool = False, postprocessor: Optional[Callable[[str], Any]] = None, show_progress: bool = False) Path[source]

Retrieve the path of a local file, downloading it if needed.

If file is not available at the local root path, it will be downloaded using requests.get. A postprocessor may be given in which case the name of the final file will be local_root/<name-of-postprocessor>/file. Removing a raw local file (ie local_root/file) will invalidate postprocessed files as well.

Parameters
  • file – A file to retrieve or download.

  • remote_root – Remote URL where the data may be retrieved using requests.get.

  • local_root – Local directory where the file may be cached.

  • force – If True, always download and apply processing (if applicable). Existing files will be overwritten.

  • postprocessor – A function which takes a single argument input_path and returns a pickleable type.

  • show_progress – If True, show a progress bar. Requires the tqdm package.

Returns

An absolute path to the data.

Raises
  • ValueError – If local root path does not exist or is not a directory.

  • ValueError – If the local file does not exist and remote==None.

  • ModuleNotFoundError – If the tqdm package is not installed but show_progress==True.

rics.utility.misc.read_env_or_literal(arg: str, default: ~typing.Union[~typing.Literal[<_NoDefault.NO_DEFAULT: '<no-default>'>], str] = _NoDefault.NO_DEFAULT, env_marker: str = '@') str[source]

Read an environment variable if arg if prefixed by env_marker, otherwise return arg as-is.

Parameters
  • arg – A literal value or environment variable to read.

  • env_marker – A prefix which indicates that arg should be interpreted as environment variable name.

  • default – Default value to use if the variable denoted by arg doesn’t exist.

Returns

A processed version arg where the final response is ans_type(processed-arg).

Raises

ValueError – If arg does not start with env_marker and enforce_env_var is True.

Notes

The constructor of desired_return_type may raise errors not listed here.

rics.utility.misc.serializable(obj: Any) bool[source]

Check if obj is serializable using Pickle.

Serializes to memory for speed.

Parameters

obj – An object to attempt to serialize.

Returns

True if obj was pickled without issues.

rics.utility.plotting module

Plotting utility methods.

rics.utility.plotting.configure() None[source]

Call all configure-functions in this module.

See this demo notebook for an example of figures rendered using these settings.

rics.utility.plotting.configure_seaborn() None[source]

Configure Seaborn figure plotting.

Caveat Emptor: May do strange stuff 👻.

Raises

ModuleNotFoundError – If Seaborn is not installed.

rics.utility.plotting.configure_matplotlib() None[source]

Configure Matplotlib figure plotting.

Caveat Emptor: May do strange stuff 👻.

Raises

ModuleNotFoundError – If matplotlib is not installed.

rics.utility.strings module

String utility methods for Python applications.

rics.utility.strings.without_suffix(arg: str, suffix: str) str[source]

Remove suffix from the tail of arg.

rics.utility.strings.without_prefix(arg: str, prefix: str) str[source]

Remove prefix from the head of arg.

Module contents

Utility modules.

rics.utility.configure_stuff(level: Union[int, str] = 20, matplotlib_level: Union[int, str] = 30) None[source]

Configure a bunch of stuff to match my personal preferences.

Caveat Emptor: May do strange stuff 👻.

Parameters
  • level – Root log level.

  • matplotlib_level – Matplotlib log level.