Named tuple and default values for optional keyword arguments

Python 3.7 Use the defaults parameter. >>> from collections import namedtuple >>> fields = (‘val’, ‘left’, ‘right’) >>> Node = namedtuple(‘Node’, fields, defaults=(None,) * len(fields)) >>> Node() Node(val=None, left=None, right=None) Or better yet, use the new dataclasses library, which is much nicer than namedtuple. >>> from dataclasses import dataclass >>> from typing import Any >>> … Read more

Serializing a Python namedtuple to json

If it’s just one namedtuple you’re looking to serialize, using its _asdict() method will work (with Python >= 2.7) >>> from collections import namedtuple >>> import json >>> FB = namedtuple(“FB”, (“foo”, “bar”)) >>> fb = FB(123, 456) >>> json.dumps(fb._asdict()) ‘{“foo”: 123, “bar”: 456}’

What are “named tuples” in Python?

Named tuples are basically easy-to-create, lightweight object types. Named tuple instances can be referenced using object-like variable dereferencing or the standard tuple syntax. They can be used similarly to struct or other common record types, except that they are immutable. They were added in Python 2.6 and Python 3.0, although there is a recipe for … Read more