Modifying a namedtuple's constructor arguments via subclassing? Modifying a namedtuple's constructor arguments via subclassing? python python

Modifying a namedtuple's constructor arguments via subclassing?


You almost had it :-) There are just two little corrections:

  1. The new method needs a return statement
  2. The super call should have two arguments, cls and Status

The resulting code looks like this:

import collectionsclass Status(collections.namedtuple("Status", "started checking start_after_check checked error paused queued loaded")):    __slots__ = ()    def __new__(cls, status):        return super(cls, Status).__new__(cls, status & 1, status & 2, status & 4, status & 8, status & 16, status & 32, status & 64, status & 128)

It runs cleanly, just like you had expected:

>>> print Status(47)Status(started=1, checking=2, start_after_check=4, checked=8, error=0, paused=32, queued=0, loaded=0)


I'd avoid super unless you're explicitly catering to multiple inheritance (hopefully not the case here;-). Just do something like...:

def __new__(cls, status):    return cls.__bases__[0].__new__(cls,                                    status & 1, status & 2, status & 4,                                    status & 8, status & 16, status & 32,                                    status & 64, status & 128)