default values for namedtuple

2

In creating a class I can set some default values:

class Point:
    def __init__(self, x, y, z=0):
        self.x = x
        self.y = y
        self.z = z

How to proceed in the same way for namedtuple?

from collection import namedtuple
Point = namedtuple('Point', 'x, y, z')
    
asked by anonymous 18.08.2017 / 03:49

2 answers

1

Subclass the result of namedtuple and rewrite the value of __new__ as follows:

from collections import namedtuple
class Move(namedtuple('Point', 'x, y, z')):
    def __new__(nome, piece, start, to, captured=None, promotion=None):
        # adicionar valores padrao
        return super(Point, nome).__new__(nome, x, y, z=0)
    
18.08.2017 / 13:59
1

In python3 use .__new__.__defaults__ to assign default values.

Points = namedtuple('Points', 'x y z')
Points.__new__.__defaults__ = (None,None,'Foo')
Points()
Points(x=None, y=None, z='Foo')
    
18.08.2017 / 18:16