I am interested in building agent-based models of economic systems in Python. Typical model might have many thousands of agents (i.e., firms, consumers, etc).
Typical firm agent class might look something like:
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 thus I could write the 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 use of __slots__
is generally discouraged. I am wondering if this be a legitimate/advisable use case for __slots__
.
The __slots__
feature is specifically meant to save memory when creating a large number of instances. Quoting the __slots__
documenation:
By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.
The default can be overridden by defining
__slots__
in a new-style class definition. The__slots__
declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because__dict__
is not created for each instance.
Sounds like you are using slots for exactly the right reasons.
What is discouraged is to use __slots__
for the no-dynamic-attributes side effect; you should use a metaclass for that instead.