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,


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(TemplateContainer, cls).__new__(cls, length, width, color)

Now we can run

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s