Creating namedtuple classes with optional or default arguments

The Issue

Say you want to create a simple class for rectangles using named tuples:

Rectangle = namedtuple("Rectangle", "length width color")

The issue is that you don’t know the color of some of your rectangles, so you whish to set it to None or white per default. Unfortunately namedtuples do not allow that, if you try,

Rectangle(5,10)

You’ll get the error:

TypeError: new() takes exactly 3 arguments (2 given)

The Solution:

Create a subclass out of the namedtuple and override its new method to allow optional parameters:

class Rectangle(namedtuple('Rectangle', [ "length", "width", "color"])):
    def __new__(cls, length, width, color="white"):
        return super(Rectangle, cls).__new__(cls, length, width, color)

Now we can run

r = Rectangle(5, 10)
print r.color
>> "White"