Search code examples
pythonclassnamedtuple

Lightweight classes with specified fields in Python


I'm looking for something very like namedtuples:

>>> from collections import namedtuple
>>> Party = namedtuple('Party', ['guests', 'location'])
>>> p = Party(['Jed', 'Fred', 'Kathy'], "Steve's House")

which I use a wrapper class around to add extensibility:

>>> class Party(namedtuple('Party', ['guests', 'location'])):
    ...

but with two differences. I would like the fields to be mutable, and I would like inheritance to work. (Right now I don't think there's a way to have one namedtuple inherit from another).

I've heard about types.SimpleNamespace, but I don't think it allows positional arguments in creation (someone correct me if I'm wrong). I like namedtuples because they keep me from having to write __init__, __repr__, and __eq__, all of which I need for my use case.

What is important to me: built-in implementations of __init__, __repr__ and __eq__ so I don't have to write them myself. I'm going to need many (30+) of these class definitions, and some of them will have many (15+) fields.

What isn't important to me (right now): memory efficiency. I don't plan to have more than five hundred instances of these at any one time.

I'm thinking of rolling my own, but want to make sure I'm not re-inventing the wheel.


Solution

  • For anyone finding this question in 2022, the most appropriate Python feature that achieves this is now dataclasses:

    from dataclasses import dataclass
    from typing import List
    
    @dataclass
    class Party:
        guests: List[str]
        location: str