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 aNamedTuple.If the given type is of
listortuple, each item will be recursively converted to aNamedTupleprovided the items can be converted. Items that cannot be converted will still exist in the returned object.If the given type is of
listthe return value will be a newlist. This means the items are not changed in the givenobj.If the given type is of
Mapping(dict), keys that can be proper identifiers will become attributes on the returnedNamedTuple. Additionally, the attributes of the returnedNamedTupleare sorted alphabetically.If the given type is of
OrderedDict, the attributes of the returnedNamedTuplekeep the same order as the givenOrderedDictkeys.If the given type is of
SimpleNamespace, The attributes are sorted alphabetically in the returnedNamedTuple.Any identifier (key or attribute name) that starts with an underscore cannot be used as a
NamedTupleattribute.All values are recursively converted. This means a dictionary that contains another dictionary, as one of it’s values, will be converted to a
NamedTuplewith the attribute’s value also converted to aNamedTuple.
- Return type
A list with any of it’s values converted to a
NamedTuple.A tuple with any of it’s values converted to a
NamedTuple.Example
>>> from flutils.namedtupleutils import to_namedtuple >>> dic = {'a': 1, 'b': 2} >>> to_namedtuple(dic) NamedTuple(a=1, b=2)