Lightweight classes with specified fields in Python

I am looking for something very similar to namedtuples :

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

which I use a wrapper class to add extensibility:

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

but with two differences. I would like fields to change, and I would like inheritance to work. (Right now, I don’t think there is a way to inherit the same name from another).

I heard about types.SimpleNamespace , but I don't think it accepts positional arguments in creation (someone corrects me if I am wrong). I like namedtuples because they do not allow me to write __init__ , __repr__ and __eq__ , all of which I need for my use.

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

What doesn't matter to me (right now): memory efficiency. I do not plan to have more than five hundred copies of them at any time.

I think about riding on my own, but I want to make sure that I am not reinventing the wheel.

+4
source share
1 answer

For the problem, you will need 50 class definitions for less than five hundred instances., In the end? Maybe you should reconsider the problem and find a completely different approach? Tried to watch the dictionaries?

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

Than you only need the standard python dict-class class and it can easily test for the presence of a field, add fields, etc., it has init, repr and eq.

Or provide additional information about the problem.

+1
source

All Articles