convert_dictable_namedtuple¶
-
privex.helpers.collections.
convert_dictable_namedtuple
(nt_instance, typename=None, module=None, **kwargs) → Union[NamedTuple, Dict][source]¶ Convert an existing
collections.namedtuple()
instance into a dictable_namedtuple instance.Example
First we create a namedtuple type
Person
>>> from collections import namedtuple >>> Person = namedtuple('Person', 'first_name last_name')
Next we create an instance of
Person
called John Doe, and we can confirm it’s a normal namedtuple, as we can’t access first_name by item/key.>>> john = Person('John', 'Doe') >>> john['first_name'] TypeError: tuple indices must be integers or slices, not str
Using
convert_dictable_namedtuple()
, we can convertjohn
from a normalnamedtuple
, into adictable_namedtuple
.This enables many convenience features (see
dictable_namedtuple()
for more info) such as easy casting to adict
, and accessing fields by item/key (square brackets):>>> from privex.helpers import convert_dictable_namedtuple >>> d_john = convert_dictable_namedtuple(john) >>> d_john Person(first_name='John', last_name='Doe') >>> d_john['first_name'] 'John' >>> dict(d_john) {'first_name': 'John', 'last_name': 'Doe'}
- Parameters
nt_instance – An instantiated namedtuple object (using a type returned from
collections.namedtuple()
)typename (str) – Optionally, you can change the name of your instance’s class, e.g. if you provide a
Person
instance, but you set this toMan
, then this will return aMan
instance, like so:Man(first_name='John', last_name='Doe')
module (str) – Optionally, you can change the module that the type class belongs to. Otherwise it will inherit the module path from the class of your instance.
- Key bool read_only
(Default:
False
) If set toTrue
, the outputted dictable_namedtuple instance will not allow new fields to be created via attribute / item setting.- Return dictable_namedtuple
The instance you passed
nt_instance
, converted into a dictable_namedtuple