Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 696
Eli Rose Avatar asked Nov 10 '22 08:11

Eli Rose


2 Answers

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
like image 65
Alex W Avatar answered Dec 06 '22 00:12

Alex W


For a problem you need 50 class definitions for less than five hundred instances . . . in total ? Maybe you should re-consider the problem and find a very different approach ? Tried looking at dictionaries ?

item1 = {'party':'easter', 'guests': ['john', fred','kathy'], 'location':'here'}

Than you need only the standard python dict-class and can easy test field presence, add fields and so on, it has init, repr and eq.

Or provide some more information on the problem.

like image 35
henkidefix Avatar answered Dec 06 '22 01:12

henkidefix