Using __slots__ in an agent-based model written in Python
I am interested in building agent-based models of economic systems in Python. A typical model may have many thousands of agents (ie, Firms, customers, etc.).
A typical agent-operator class might look something like this:
class Firm(object):
def __init__(capital, labor, productivity):
self.capital = capital
self.labor = labor
self.productivity = productivity
In most of my models, attributes are not dynamically created, and so I could write a class using __slots__
:
class Firm(object):
__slots__ = ('capital', 'labor', 'productivity')
def __init__(capital, labor, productivity):
self.capital = capital
self.labor = labor
self.productivity = productivity
However, it seems that the usage is __slots__
usually discouraged. I'm wondering if this would be a legal / feasible use case for __slots__
.
source to share
The function __slots__
is specifically designed to save memory when creating a large number of instances. Quoting the __slots__
documenation :
By default, instances of both old and new classes have a dictionary for storing attributes. This frees up space for objects that have very few instance variables. Space consumption can become acute when creating a large number of copies.
The default can be overridden by
__slots__
defining a new style in the class definition. The declaration__slots__
takes a sequence of instance variables and reserves enough space in each instance to store the value for each variable. Space is conserved as__dict__
it is not created for every instance.
It looks like you are using slots for the right reasons.
Not recommended __slots__
for a side effect without dynamic attributes; you should use a metaclass instead.
source to share