Brian Fitzpatrick
Brian Fitzpatrick

Reputation: 2503

Can a class inherit the properies of a namedtuple?

I have a named tuple.

import collections

MyNamedTuple = collections.namedtuple('MyNamedTuple', 'prop1 prop2 foo bar')

I would like to define a class that can be initialized by these named tuples.

class MyClass():
    def __init__(self, t):
        self.prop1 = t.prop1
        self.prop2 = t.prop2
        self.foo = t.foo
        self.bar = t.bar

The larger MyNamedTuple is the more typing I have to do to define MyClass so I'm curious if there is a more efficient way to define MyClass.

Upvotes: 2

Views: 1781

Answers (1)

mgilson
mgilson

Reputation: 310069

You've got a couple options... namedtuple returns a class -- You can subclass it directly:

class MyClass(MyNamedTuple):
    ...

Of course, this means that MyClass is a tuple which might not be desirable...

You can also use the _fields attribute of the namedtuple (It's documented -- the leading underscore is to prevent property name collisions rather than to indicate that it is a "private" member)...

def __init__(self, t):
    for field in t._fields:
        setattr(self, field, getattr(t, field))

Of course, this kind of setting via introspection isn't always the most clear thing to read either (and might cause spurious linter warnings) ...

Otherwise, there isn't a really good way to make the linters happy and have really short code and writing them all out may be your best option. If the number of fields in the namedtuple is expected to change at all in the future, I'd advise that you have a unit-test that checks a freshly created MyClass against the MyNamedTuple that was used to create it to make sure that all of the properties of MyNamedTuple are being set. You could (and probably should) use the introspection from _fields to do this check.

Upvotes: 2

Related Questions