Creating namedtuple classes with optional or default arguments
23 May 2014The Issue
Say you want to create a simple class for rectangles using named tuples:
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,
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:
Now we can run