Sometimes it makes sense to cluster related data together. I tend to do so with a dict, e.g.,
self.group = dict(a=1, b=2, c=3)
print self.group[\'a\']
What about Prodict:
group = Prodict(a=1, b=2, c=3)
group.d = 4
And if you want auto type conversion and auto code complete(intelli-sense):
class Person(Prodict):
name: str
email: str
rate: int
john = Person(name='John', email='john@appleseed.com')
john.rate = 7
john.age = 35 # dynamic
If one do not care about memory footprint then dict, namedtuple, dataclass or just a class with __slots__
are good choices.
But if one have to create millions of objects with a few simple attributes then there is a solution based on recordclass library:
from recordclass import make_dataclass
C = make_dataclass("C", ('a', 'b', 'c'))
c = C(1, 2, 3)
Same with a class definition:
from recordclass import dataobject
class C(dataobject):
a:int
b:int
c:int
c = C(1, 2, 3)
It has minimal memory footprint = sizeof(PyObject_HEAD) + 3*sizeof(PyObject*)
bytes.
For comparison __slots__
-based variant require sizeof(PyGC_Head) + sizeof(PyObject_HEAD) + 3*sizeof(PyObject*)
bytes.
If you're really never defining any class methods, a dict or a namedtuple make far more sense, in my opinion. Simple+builtin is good! To each his own, though.
You can combine advantages of dict and class together, using some wrapper class inherited from dict. You do not need to write boilerplate code, and at the same time can use dot notation.
class ObjDict(dict):
def __getattr__(self,attr):
return self[attr]
def __setattr__(self,attr,value):
self[attr]=value
self.group = ObjDict(a=1, b=2, c=3)
print self.group.a
There is a new proposal that aims to implement exactly what you are looking for, called data classes. Take a look at it.
Using a class over a dict is a matter of preference. Personally I prefer using a dict when the keys are not known a priori. (As a mapping container).
Using a class to hold data means you can provide documentation to the class attributes.
Personally, perhaps the biggest reason for me to use a class is to make use of the IDEs auto-complete feature! (technically a lame reason, but very useful in practise)
I disagree that the code is more readable using a class with no methods. You usually expect functionality from a class, not only data.
So, I'd go for a dict until the need for functionality arises, and then the constructor of the class could receive a dict :-)