DEV Community

sumandari
sumandari

Posted on

Define fixed attributes dataclass with __slots__()

what is __slots__()?
see: https://wiki.python.org/moin/UsingSlots

it defines fix objects in a @dataclass

e.g dataclass without slots. we can define new_attribute in the instance

>>> @dataclass
... class Rect:
...     height: int
...     width: int
... 
>>> r = Rect(1, 2)
>>> r
Rect(height=1, width=2)
>>> r.new_attribute = 5
>>> r.new_attribute
5
Enter fullscreen mode Exit fullscreen mode

e.g dataclass with fixed attribute

>>> @dataclass
... class Circle:
...     __slots__ = ("r", )
...     r : int
... 
>>> c = Circle(10)
>>> c
Circle(r=10)
>>> c.new_attribute = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Circle' object has no attribute 'new_attribute'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)