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)

๐Ÿ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay