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.
__slots__
attribute inclass Party
suffice? – Trichoidnamedtuple
", what precise qualities are you looking for? If it's a space issue, then @chepner's suggestion to use__slots__
is a good one. – Leonie__eq__
,__repr__
and__init__
. It doesn't need to be hashable or to subclasstuple
. – Ezekielezell__repr__
and__init__
logic for every one of them. So, the amount of code it takes to define a class is important to me. – Ezekielezellnamedtuple
and borrow what you need from that. – Leonienamedtuple
does) if you try to instantiate without providing all of them. – Ezekielezell__eq__
etc, then each of your actual classes would be instances of that, which just provide the names of that class's attributes. – Spooky__init__
,__repr__
and__eq__
. – Ezekielezell