Is it possible to create a class that inherits from several instances of namedtuple , or to create something with the same effect (with an immutable type that combines the fields of the base types)? I did not find a way to do this.
This example illustrates the problem:
>>> class Test(namedtuple('One', 'foo'), namedtuple('Two', 'bar')): >>> pass >>> t = Test(1, 2) TypeError: __new__() takes 2 positional arguments but 3 were given >>> t = Test(1) >>> t.foo 1 >>> t.bar 1
The problem is that namedtuple does not use super to initialize its base class, as seen when creating:
>>> namedtuple('Test', ('field'), verbose=True) [...] class Test(tuple): [...] def __new__(_cls, field,): 'Create new instance of Test(field,)' return _tuple.__new__(_cls, (field,))
Even if I decided to write my own version of namedtuple to fix this, it's not clear how to do this. If there are several namedtuple instances in the class MRO, they will have to split up one instance of the tuple base class. To do this, they would have to coordinate on which namedtuple uses the range of indices in the base tuple.
Is there an easier way to achieve multiple inheritance with namedtuple or something similar? Has anyone already implemented this somewhere?
source share