nestedtext.dumps

nestedtext.dumps(obj, *, sort_keys=False, indent=4, renderers=None, default=None, level=0)[source]

Recursively convert object to NestedText string.

Parameters
  • obj – The object to convert to NestedText.

  • sort_keys (bool or func) – Dictionary items are sorted by their key if sort_keys is true. If a function is passed in, it is used as the key function.

  • indent (int) – The number of spaces to use to represent a single level of indentation. Must be one or greater.

  • renderers (dict) – A dictionary where the keys are types and the values are render functions (functions that take an object and convert it to a string). These will be used to convert values to strings during the conversion.

  • default (func or 'strict') – The default renderer. Use to render otherwise unrecognized objects to strings. If not provided an error will be raised for unsupported data types. Typical values are repr or str. If ‘strict’ is specified then only dictionaries, lists, strings, and those types specified in renderers are allowed. If default is not specified then a broader collection of value types are supported, including None, bool, int, float, and list- and dict-like objects. In this case Booleans is rendered as ‘True’ and ‘False’ and None and empty lists and dictionaries are rendered as empty strings.

  • level (int) – The number of indentation levels. When dumps is invoked recursively this is used to increment the level and so the indent. Generally not specified by the user, but can be useful in unusual situations to specify an initial indent.

Returns

The NestedText content.

Raises

NestedTextError – if there is a problem in the input data.

Examples

>>> import nestedtext as nt

>>> data = {
...     'name': 'Kristel Templeton',
...     'sex': 'female',
...     'age': '74',
... }

>>> try:
...     print(nt.dumps(data))
... except nt.NestedTextError as e:
...     print(str(e))
name: Kristel Templeton
sex: female
age: 74

The NestedText format only supports dictionaries, lists, and strings and all leaf values must be strings. By default, dumps is configured to be rather forgiving, so it will render many of the base Python data types, such as None, bool, int, float and list-like types such as tuple and set by converting them to the types supported by the format. This implies that a round trip through dumps and loads could result in the types of values being transformed. You can restrict dumps to only supporting the native types of NestedText by passing default=’strict’ to dumps. Doing so means that values that are not dictionaries, lists, or strings generate exceptions; as do empty dictionaries and lists.

>>> data = {'key': 42, 'value': 3.1415926, 'valid': True}

>>> try:
...     print(nt.dumps(data))
... except nt.NestedTextError as e:
...     print(str(e))
key: 42
value: 3.1415926
valid: True

>>> try:
...     print(nt.dumps(data, default='strict'))
... except nt.NestedTextError as e:
...     print(str(e))
42: unsupported type.

Alternatively, you can specify a function to default, which is used to convert values to strings. It is used if no other converter is available. Typical values are str and repr.

>>> class Color:
...     def __init__(self, color):
...         self.color = color
...     def __repr__(self):
...         return f'Color({self.color!r})'
...     def __str__(self):
...         return self.color

>>> data['house'] = Color('red')
>>> print(nt.dumps(data, default=repr))
key: 42
value: 3.1415926
valid: True
house: Color('red')

>>> print(nt.dumps(data, default=str))
key: 42
value: 3.1415926
valid: True
house: red

You can also specify a dictionary of renderers. The dictionary maps the object type to a render function.

>>> renderers = {
...     bool: lambda b: 'yes' if b else 'no',
...     int: hex,
...     float: lambda f: f'{f:0.3}',
...     Color: lambda c: c.color,
... }

>>> try:
...    print(nt.dumps(data, renderers=renderers))
... except nt.NestedTextError as e:
...     print(str(e))
key: 0x2a
value: 3.14
valid: yes
house: red

If the dictionary maps a type to None, then the default behavior is used for that type. If it maps to False, then an exception is raised.

>>> renderers = {
...     bool: lambda b: 'yes' if b else 'no',
...     int: hex,
...     float: False,
...     Color: lambda c: c.color,
... }

>>> try:
...    print(nt.dumps(data, renderers=renderers))
... except nt.NestedTextError as e:
...     print(str(e))
3.1415926: unsupported type.

Both default and renderers may be used together. renderers has priority over the built-in types and default. When a function is specified as default, it is always applied as a last resort.