[Python-ideas] Add optional defaults to namedtuple
Ethan Furman
ethan at stoneleaf.us
Wed Nov 30 10:09:48 EST 2016
On 11/30/2016 02:32 AM, Jelte Fennema wrote:
> It would be nice to have a supported way to add defaults to namedtuple,
> so the slightly hacky solution here does not have to be used:
> http://stackoverflow.com/a/18348004/2570866
Actually, the solution right below it is better [1]:
--> from collections import namedtuple
--> class Node(namedtuple('Node', ['value', 'left', 'right'])):
--> __slots__ = ()
--> def __new__(cls, value, left=None, right=None):
--> return super(Node, cls).__new__(cls, value, left, right)
But even more readable than that is using the NamedTuple class from my aenum [3] library (and on SO as [3]):
--> from aenum import NamedTuple
--> class Node(NamedTuple):
--> val = 0
--> left = 1, 'previous Node', None
--> right = 2, 'next Node', None
shamelessly-plugging-my-own-solutions'ly yrs,
--
~Ethan~
[1] http://stackoverflow.com/a/16721002/208880
[2] https://pypi.python.org/pypi/aenum
[3] http://stackoverflow.com/a/40891597/208880
More information about the Python-ideas
mailing list