I would like to limit the max number of instance of a dataclass and to know the index of the instance. This is the behaviour that I want:
Veget('tomato', 2.4, 5)
Veget('salad', 3.5, 2)
Veget('carot', 1.2, 7)
for Veget in Veget.instances:
print(Veget)
Veget(index=0, name='tomato', price=2.4, quantity=5)
Veget(index=1, name='salad', price=3.5, quantity=2)
Veget(index=2, name='carot', price=1.2, quantity=7)
I tried the following, which does handle the creation limit:
from dataclasses import dataclass
MAX_COUNT = 3
class Limited:
instances = []
def __new__(cls, *_):
if len(cls.instances) < MAX_COUNT:
newobj = super().__new__(cls)
cls.instances.append(newobj)
return newobj
else:
raise RuntimeError('Too many instances')
@dataclass
class Veget(Limited):
name: str
price: float
quantity: int
But it won't show the index when printed:
Veget(name='tomato', price=2.4, quantity=5)
Veget(name='salad', price=3.5, quantity=2)
Veget(name='carot', price=1.2, quantity=7)