Since this question has been asked, the dataclasses
module has been proposed and accepted into Python. This module has a lot of overlapping use cases with namedtuples
but with some more flexibility and power. In particular, you can specify a factory function for when you want to specify a default for a mutable field.
from typing import List
from dataclasses import dataclass, field
@dataclass
class Node:
val: str
left: List["Node"] = field(default_factory=list)
right: List["Node"] = field(default_factory=list)
In a data class you specify the types of the various fields, so in this case I had to fill in a few blanks and assume that val
would be a string and that left
and right
would both be lists of other Node
objects.
Since right
and left
are the left hand side of an assignment in the class definition, they are optional arguments when we initialize a Node
object. Further, we could supply a default value, but instead we supplied a default factory, which is a function that is called with 0 arguments whenever we initialize a Node
object without specifying those fields.
For example:
node_1 = Node('foo')
# Node(val='foo', left=[], right=[])
node_2 = Node('bar', left=[node_1])
# Node(val='bar', left=[Node(val='foo', left=[], right=[])], right=[])
node_3 = Node('baz')
# Node(val='baz', left=[], right=[])
node_4 = Node('quux', left=[node_2], right=[node_3])
# Node(val='quux', left=[Node(val='bar', left=[Node(val='foo', left=[], right=[])], right=[])], right=[Node(val='baz', left=[], right=[])])
Personally I find myself reaching for dataclasses
over namedtuples
for any application where I need more than just the thinnest container for data.