neclib.core.files.toml#

TOML file handling.

Aliases#

read_file

Read a file, if it’s accessible via any available way.

read(__file, /)[source]#

Read and parse a TOML file.

Parameters:

__file (Union[PathLike, str, IO]) – Path to the TOML file or a file-like object.

Returns:

The parsed content.

Return type:

parsed

Examples

>>> neclib.core.toml.read("path/to/pyproject.toml")

You can also pass a file-like object:

>>> with open("pyproject.toml") as f:
...     neclib.core.toml.read(f)
flatten(doc, /, *, prefix='', sep='.')[source]#

Flatten a parsed TOML object.

Parameters:
  • doc (Dict[str, Any]) – TOML document or TOML Table to be flattened.

  • prefix (str) – Prefix to be added to the keys.

  • sep (str) – Separator to be used to join keys.

Returns:

The flattened TOML document.

Return type:

flattened

Notes

This function flattens dict-like objects recursively, but InlineTable objects will be kept as is. This feature comes from the following motivations:

  • TOML files should be well-structured by the parameters semantics.

  • Deeply nested dict-like object is hard to handle, so we flatten them.

  • Flattening all dict-like objects will remove ability to store structured-parameter (dict-like object) in TOML files.

The author never felt this implementation a good one, since it contradicts the TOML specification: “inline-tables are just a short-hand definition of tables”, which implies they should be treated equivalently. If the alternative method to flatten TOML document is found, this function will employ it.

Examples

>>> neclib.core.toml.flatten({"a": {"b": 1, "c": 2}, "d": 3})
{"a.b": 1, "a.c": 2, "d": 3}
to_string(__mapping, /)[source]#

Convert a mapping to a TOML string.

Parameters:

__mapping (Mapping[str, Any]) – Mapping object to be converted.

Returns:

TOML format representation of given mapping object.

Return type:

toml_string

Examples

>>> neclib.core.toml.to_string({"a": 1, "b": 2})
'a = 1\nb = 2'