text
Tools for loading, completing, and writing text and configuration files.
Parameters that are known at program start are used to initialize the classes so that, at runtime, the information only available then can flow through a preconfigured pipe of callable objects to yield the desired result.
- class TextResourceLoader(package, path='resources', not_found=NotFound.RAISE, encoding='utf-8')[source]
Bases:
ArgRepr
Load text files from a resource directory within a python package.
- Parameters:
package (str) – Name of the python package under which the text file is located.
path (str, optional) – Directory under which the text file is located within the python package or full path to the text file. If not fully specified here, the path must be completed on calling the instance. Defaults to “resources”.
not_found (str, optional) – What to do if the specified file is not found. One of “ignore”, “warn”, or “raise”. Defaults to “raise”. Use the
NotFound
enum to avoid typos!encoding (str, optional) – Encoding of the text file. Defaults to “utf-8”.
See also
- __call__(path='')[source]
Load text file from a directory within the specified python package.
- Parameters:
path (str, optional) – Path (including file name) relative to the path specified at instantiation. Defaults to an empty string, which results in an unchanged path on concatenation.
- Returns:
Decoded contents of the specified text file.
- Return type:
str
- class TemplateRenderer(template, mapping=None, **kwargs)[source]
Bases:
object
Substitute bash-style “${key}” placeholders in a template string.
This is a light wrapper around the standard library’s
string.Template
, calling its methodsafe_substitute
upon instantiation and its methodsubstitute
when calling the (callable) instance. At first, not all keys need to be provided, but when the object is called and the substitution is finalized, all keys must have been provided.- Parameters:
template (str) – String with bash-style “${key}” placeholders to substitute.
mapping (dict, optional) – Dictionary-like mapping with the placeholders to substitute as keys and the values to substitute as values. Defaults to
None
.**kwargs – Keyword arguments replace respective placeholders with whatever value is passed, overwriting values in mapping.
Note
Instances evaluate to
True
if all keys were provided at instantiation and toFalse
if there are still keys missing.- __call__(mapping=None, **kwargs)[source]
Substitute bash-style “${key}” placeholders in the wrapped template.
- Parameters:
mapping (dict, optional) – Dictionary-like mapping with the placeholders to substitute as keys and the values to substitute as values. Defaults to
None
.**kwargs – Keyword arguments replace respective placeholders with whatever value is passed, overwriting values in mapping.
- Returns:
String with all placeholders substituted.
- Return type:
str
- Raises:
KeyError – When a value for one or more placeholders is still missing.
ValueError – When a key is not a valid python identifier.
- property identifiers
List of identifiers that still need to be interpolated.
- class FormFiller(mapping=None, **kwargs)[source]
Bases:
object
Substitute bash-style “${key}” placeholders in a template string.
This is a light wrapper around the standard library’s
string.Template
, first caching a dictionary and optional keywords on instantiation, and then calling its methodsubstitute
with these cached values when calling the (callable) object with the template string.- Parameters:
mapping (dict, optional) – Dictionary-like mapping with the placeholders to substitute as keys and the values to substitute as values. Defaults to
None
.**kwargs – Keyword arguments replace respective placeholders with whatever value is passed, overwriting respective values in mapping.
Note
Instances evaluate to
False
if no keys were provided at instantiation and toTrue
if there are any keys cached.- __call__(template, mapping=None, **kwargs)[source]
Substitute bash-style “${key}” placeholders in a string template.
- Parameters:
template (str) – String with bash-style “${key}” placeholders to substitute.
mapping (dict, optional) – Dictionary-like mapping with the placeholders to substitute as keys and the values to substitute as values. Defaults to
None
.**kwargs – Keyword arguments replace respective placeholders with whatever value is passed, overwriting the cached mapping.
- Returns:
String with all placeholders substituted.
- Return type:
str
- Raises:
KeyError – When a value for one or more placeholders is still missing.
ValueError – When a key is not a valid python identifier.
- class JsonReader(path='', not_found=NotFound.RAISE, gzipped=None, **kwargs)[source]
Bases:
ArgRepr
Light wrapper around python’s own
json.load
function.- Parameters:
path (str, optional) – Directory under which the JSON file is located or full path to the JSON file. If not fully specified here, the path can be completed on calling the instance. Defaults to the current working directory of the python interpreter.
not_found (str, optional) – What to do if the specified JSON file is not found. One of “ignore”, “warn”, or “raise”. Defaults to “raise”. Use the
NotFound
enum to avoid typos!gzipped (bool, optional) – Try to read a gzip-compressed JSON file if
True
and a plain text file ifFalse
. If left atNone
, which is the default, files will be interpreted as gzip-compressed if their name ends in “.gz” and as plain text if it does not.**kwargs – Additional keyword arguments will be forwarded to the builtin
open
or thegzip.open
function, depending on gzipped. The mode to open the file is hardcoded to"rt"
and will, therefore, be dropped from the keyword arguments.
See also
- __call__(path='')[source]
Read a specific JSON file.
If not_found is set to “warn” or “ignore” and the file cannot be found, and empty dictionary is returned.
- Parameters:
path (str, optional) – Path (including file name) to the JSON file to read. If it starts with a backslash, it will be interpreted as absolute, if not, as relative to the path specified at instantiation. Defaults to an empty string, which results in an unchanged path.
- Returns:
The parsed contents of the JSON file.
- Return type:
dict or list
- class JsonWriter(path='', overwrite=False, create=False, gzipped=None, prune=False, default=None, indent=None, **kwargs)[source]
Bases:
ArgRepr
Partial of the
dump
function in python’s ownjson
package.- Parameters:
path (str, optional) – Path (including file name) to save the JSON file to. May include any number of string placeholders (i.e., pairs of curly brackets) that will be interpolated when instances are called. Defaults to the current working directory of the python interpreter.
overwrite (bool, optional) – What to do if the JSON file to write already exists. Defaults to
False
.create (bool, optional) – What to do if the directory where the JSON file should be saved does not exist. Defaults to
False
.gzipped (bool, optional) – Write the JSON to a gzip-compressed JSON file if
True
and a plain text file ifFalse
. If left atNone
, which is the default, file names ending in “.gz” will trigger compression whereas all other extensions (if any) will not.prune (bool, optional) – If
True
, keys that are not of a basic type (str
,int
,float
,bool
,None
) will be skipped instead of raising aTypeError
. Defaults toFalse
.default (callable, optional) – Called on objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a
TypeError
. Defaults toNone
, which raises aTypeError
.indent (int or str, optional) – If a positive integer or string, JSON array elements and object members will be pretty-printed with that indent level. A positive integer indents that many spaces per level. A string (such as “ “) is used to indent each level. If zero, negative, or “” (the empty string), only newlines are inserted. If
None
(the default), the most compact representation is used.**kwargs – Additional keyword arguments will be forwarded to the builtin
open
or thegzip.open
function, depending on gzipped. The mode to open the file is hardcoded to with"wt"
or"xt"
(depending on create) and will, therefore, be dropped from the keyword arguments.
- __call__(obj, *parts)[source]
Serialize the given object and write it to JSON file.
- Parameters:
obj (dict or list) – The object to save as JSON.
*parts (str, optional) – Fragments that will be interpolated into the path string given at instantiation. Obviously, there must be at least as many as there are placeholders in the path.
- Returns:
An empty tuple.
- Return type:
tuple
- property mode
The mode to open the target file with.
- class TomlReader(path='', not_found=NotFound.RAISE, parse_float=<class 'float'>, **kwargs)[source]
Bases:
ArgRepr
Light wrapper around the python standard library’s
tomllib.load
.- Parameters:
path (str, optional) – Directory under which the TOML file is located or full path to the TOML file. If not fully specified here, the path can be completed or changed on calling the instance. Defaults to the current working directory of the python interpreter.
not_found (str, optional) – What to do if the specified TOML file is not found. One of “ignore”, “warn”, or “raise”. Defaults to “raise”. Use the
NotFound
enum to avoid typos!parse_float (callable, optional) – Will be called with the string of every TOML float to be decoded. Defaults to
float
.**kwargs – Additional keyword arguments will be forwarded python`s builtin
open
function. Since the mode must be"rb"
, it is dropped from the keyword arguments.
See also
- __call__(path='')[source]
Read a specific TOML file.
If not_found is set to “warn” or “ignore” and the file cannot be found, an empty dictionary is returned.
- Parameters:
path (str) – Path (including file name) to the TOML file to read. If it starts with a backslash, it will be interpreted as absolute, if not, as relative to the path specified at instantiation. Defaults to an empty string, which results in an unchanged path.
- Returns:
The parsed contents of the TOML file.
- Return type:
dict
- class TomlWriter(path='', overwrite=False, create=False, prune=False, multiline_strings=False, indent=4, **kwargs)[source]
Bases:
ArgRepr
Partial of the
dump
function in thetomli-w
package.- Parameters:
path (str, optional) – Path (including file name) to save the TOML file to. May include any number of string placeholders (i.e., pairs of curly brackets) that will be interpolated when instances are called. Defaults to the current working directory of the python interpreter.
overwrite (bool, optional) – What to do if the TOML file to write already exists. Defaults to
False
.create (bool, optional) – What to do if the directory where the TOML file should be saved does not exist. Defaults to
False
.prune (bool, optional) – Whether to silently drop non-string keys and
None
values from the dictionary-like object to save as TOML. Defaults toFalse`
.multiline_strings (bool, optional) – Whether to preserve newline bytes in multiline strings. Defaults to
False
.indent (int, optional) – Number of spaces for array indentation. Defaults to 4.
**kwargs – Additional keyword arguments will be forwarded python`s builtin
open
function. The mode is determined by the overwrite argument and is, therefore, dropped from the keyword arguments.
- __call__(toml, *parts)[source]
Serialize a dictionary-like object and write it to TOML file.
- Parameters:
toml (dict) – The dictionary-like object to save as TOML.
*parts (str, optional) – Fragments that will be interpolated into the path string given at instantiation. Obviously, there must be at least as many as there are placeholders in the path.
- Returns:
An empty tuple.
- Return type:
tuple
- property mode
The mode to open the target file with.
- class YamlReader(path='', not_found=NotFound.RAISE, loader=<class 'yaml.loader.Loader'>, **kwargs)[source]
Bases:
ArgRepr
Light wrapper around pyyaml’s
yaml.load
function.- Parameters:
path (str, optional) – Directory under which the YAML file is located or full path to the YAML file. If not fully specified here, the path can be completed on calling the instance. Defaults to the current working directory of the python interpreter.
not_found (str, optional) – What to do if the specified YAML file is not found. One of “ignore”, “warn”, or “raise”. Defaults to “raise”. Use the
NotFound
enum to avoid typos!loader (type, optional) – The loader class to use. Defaults to
Loader
**kwargs – Additional keyword arguments will be forwarded python`s builtin
open
function. The mode is hard-coded to"rb"
and is dropped from the keyword arguments.
See also
- __call__(path='')[source]
Read a specific YAML file.
If not_found is set to “warn” or “ignore” and the file cannot be found, and empty dictionary is returned.
- Parameters:
path (str, optional) – Path (including file name) to the YAML file to read. If it starts with a backslash, it will be interpreted as absolute, if not, as relative to the path specified at instantiation. Defaults to an empty string, which results in an unchanged path.
- Returns:
The parsed contents of the YAML file.
- Return type:
dict or list
- class YamlParser(loader=<class 'yaml.loader.Loader'>)[source]
Bases:
ArgRepr
Light wrapper around pyyaml’s
yaml.load
function.- Parameters:
loader (type, optional) – The loader class to use. Defaults to
Loader
- class YamlWriter(path='', overwrite=False, create=False, **kwargs)[source]
Bases:
ArgRepr
Partial of the
dump
function in thepyyaml
package.- Parameters:
path (str, optional) – Path (including file name) to save the YAML file to. May include any number of string placeholders (i.e., pairs of curly brackets) that will be interpolated when instances are called. Defaults to the current working directory of the python interpreter.
overwrite (bool, optional) – What to do if the YAML file to write already exists. Defaults to
False
.create (bool, optional) – What to do if the directory where the YAML file should be saved does not exist. Defaults to
False
.**kwargs – Additional keyword arguments will be forwarded to the wrapped
dump
method of thepyyaml
package. See its documentation for details.
- __call__(yml, *parts)[source]
Serialize the given object and write it to YAML file.
- Parameters:
yml (dict or list) – The object to save as YAML.
*parts (str, optional) – Fragments that will be interpolated into the path string given at instantiation. Obviously, there must be at least as many as there are placeholders in the path.
- Returns:
An empty tuple.
- Return type:
tuple
- property mode
The mode to open the target file with.