This tutorial will teach you about Python data-classes. They operate similar to C# record’s.
- Python 3.7 or later
- Know basics of Python 3 if not read here
- Know Python 3 objects if not read here
- Knowledge of Python 3 typing module will help
- Knowledge of Python 3 decorators will help
What are they?
Data Classes in Python allows for adding special methods like
__repr__ to a class decorated with the
Before we create a data-class we will first need to import it from the Python standard library. After it has been imported we can simply place the decorator above a class.
After a class has been decorated we just need to define some properties. This can be seen in the code below.
In this code we are creating two user objects, as you can see as well as passing arguments by position we can also pass them by key. We can also set defaults this has been used on the age property where we give it a default value of 0.
When the code is run we will get the output shown below. As you can see when printed it results in a nicely formatted output, this has been made possible by the automatically generated
User(first_name='Leo', age=19) User(first_name='Steve', age=20)
We can also have a property be another data-class.
When creating a data-class we can choose which features are enabled, by default (as of Python 3.7) the default will create a
__eq__ and will not create order methods such as
In the code example below we are creating the same user class without
__repr__. As you can see we simply call the decorator like we would a normal function and pass in the keyword argument.
As you can see we don’t get the formatted data
What happens if we wanted to stop the modification of the object once created. Well in Python we can do this, however we have to tell the data-class to freeze the object. This is shown the example below.
This provides protection from accidental modification. But should not be used as a security feature.
As you can see in the output below when we try to change a value we will get a
Traceback (most recent call last): File "user.py", line 9, in <module> user_one.age += 1 File "<string>", line 4, in __setattr__ dataclasses.FrozenInstanceError: cannot assign to field 'age'
Converting into dict
Data-classes can come in very handy when working with JSON. To get our class ready for passing into
json.dumps we use the
asdict() function to convert it into a dict.
There is more functionality in the data-class which is not covered in this tutorial, if you want to learn more go to the official Python docs here.