Python dataclasses and __slots__
Hello, blog!
I was learning Binary Search Trees (BST) from Scott Barrett's Python DSA Course [2] and was using the following code to define a node.
I got ChatGPT to teach me about Binary Search Trees and it generated the following code:
Now, I was curious what this @dataclass annotation with 'slots=True' argument is.
Looking into this, I learned that there is a 'dataclasses' module in the standard Python library (3.7+). '@dataclass' is a decorator function that lives inside that module. You use it as `@dataclass' on top of a class definition. It modifies the class to automatically generate methods like '__init__' , '__repr__', '__eq__', etc.
Dataclasses
Slots
In the above example, you can see that there's an error in the x2.var0 (it should be x2.var_0) but this doesn't cause an error. However, we can 'catch' these kind of errors with the __slots__ class variable. The __slots__ is a class variable that is assigned a sequence of strings that are variable names used by instances.
That's it for now; thank you for reading! :)
References:
[1] https://seneca-ictoer.github.io/data-structures-and-algorithms/J-Binary-Search-Trees/intro-to-bst
[2] https://www.udemy.com/course/data-structures-algorithms-python/?srsltid=AfmBOopsoaoMwfMTDy0I3gvY96BinH-hYbzpyfK55qBthxfPdAneUhdU
[3] https://wiki.python.org/moin/UsingSlots
[4] https://docs.python.org/3/library/dataclasses.html
Comments
Post a Comment