Named Tuples

flutils offers the following named-tuple utility functions:

to_namedtuple(obj)[source]

Convert particular objects into a namedtuple.

Parameters

obj (Union[List, Mapping, NamedTuple, SimpleNamespace, Tuple]) – The object to be converted (or have it’s contents converted) to a NamedTuple.

If the given type is of list or tuple, each item will be recursively converted to a NamedTuple provided the items can be converted. Items that cannot be converted will still exist in the returned object.

If the given type is of list the return value will be a new list. This means the items are not changed in the given obj.

If the given type is of Mapping (dict), keys that can be proper identifiers will become attributes on the returned NamedTuple. Additionally, the attributes of the returned NamedTuple are sorted alphabetically.

If the given type is of OrderedDict, the attributes of the returned NamedTuple keep the same order as the given OrderedDict keys.

If the given type is of SimpleNamespace, The attributes are sorted alphabetically in the returned NamedTuple.

Any identifier (key or attribute name) that starts with an underscore cannot be used as a NamedTuple attribute.

All values are recursively converted. This means a dictionary that contains another dictionary, as one of it’s values, will be converted to a NamedTuple with the attribute’s value also converted to a NamedTuple.

Return type

list

A list with any of it’s values converted to a NamedTuple.

tuple

A tuple with any of it’s values converted to a NamedTuple.

NamedTuple.

Example

>>> from flutils.namedtupleutils import to_namedtuple
>>> dic = {'a': 1, 'b': 2}
>>> to_namedtuple(dic)
NamedTuple(a=1, b=2)