JiangFeng
JiangFeng

Reputation: 355

Python - how to store many classes with out using too much memory?

Say I have a class to store some different types of values, and I got a bunch number of these classes. How can I store them neatly without using too much memory? Or is there a way of not using this stupid class?

class item:
    id = int()
    time = float()
    flag = int()
    description =str()

    def __init__(self, id, time, flag, description):
        self.id = id
        self.time = time
        self.flag = flag
        self.description = description


dataBaseSize = 134217728

dataList = list()

for i in range(dataBaseSize):
    new = item(i, 0, 0, "i")
    dataList.append(new)

Doing something like this would cause the memory to explode. So How can I optimize this in Python?

Upvotes: 3

Views: 360

Answers (1)

ramazan polat
ramazan polat

Reputation: 7900

You can use __slots__ trick.

There will be a significant difference in memory usage(40 to 50%).

class MyClass(object):
    __slots__ = ['name', 'identifier']
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier

Upvotes: 1

Related Questions