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

As mentioned above, 'dataclasses' are a python feature (3.7+) that automatically generate boilerplate code for classes that primarily store data.

For example, if you're creating a game, then the Hero class would look like the following:

Using @dataclass annotation, you can make the code more readable:

As mentioned in the docs[4], there are quite a few arguments that can be passed to the dataclass decorator, I'll explain a little bit about what the 'slots' argument does below but it's worth looking into the rest of the arguments if you want other features for your data. e.g. 'frozen=True' for immutability.

Slots

Explanation for Slots is done really well in resource [3]. From my understanding, whenever you create a new instance of a class (i.e. an object), Python creates an __dict__ attribute for the class. The __dict__ attribute is a dictionary whose keys are the variable names and whose values are the variable values. This allows for dynamic variable creation but can also lead to uncaught errors.


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

Popular posts from this blog

RAID! No, not that one

Working with APIs using Python

Sorting Algorithms