A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://stackoverflow.com/questions/3357581/using-python-class-as-a-data- below:

Using Python class as a data container

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 in the context of limited memory 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.

Since 0.15 there is an option fast_new for faster instance creation:

C = make_dataclass("C", ('a', 'b', 'c'), fast_new=True)

or

class C(dataobject, fast_new=True):
    a:int
    b:int
    c:int    

This option accelerates the instance creation twice.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4