Enchanted Code

Dataclasses In Python

3 minutes read

Intro

This tutorial will teach you about Python data-classes. They operate similar to C# record’s.

Requirements

  • 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 __init__ and __repr__ to a class decorated with the @dataclass decorator.

Creating

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from dataclasses import dataclass

@dataclass
class User:
    first_name: str
    age: int = 0

user_one = User("Leo", 19)
user_two = User(
    first_name="Steve",
    age=20
)

print(user_one)
print(user_two)

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 __repr__ method.

1
2
User(first_name='Leo', age=19)
User(first_name='Steve', age=20)

We can also have a property be another data-class.

Customised Creation

When creating a data-class we can choose which features are enabled, by default (as of Python 3.7) the default will create a __init__, __repr__, __eq__ and will not create order methods such as __lt__.

Disable Repr

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from dataclasses import dataclass

@dataclass(repr=False)
class User:
    first_name: str
    age: int = 0

user_one = User("Leo", 19)

print(user_one)

As you can see we don’t get the formatted data

1
<__main__.User object at 0x7f30fce14730>

Freezing

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from dataclasses import dataclass

@dataclass(frozen=True)
class User:
    first_name: str
    age: int = 0

user_one = User("Leo", 19)
user_one.age += 1
print(user_one)

As you can see in the output below when we try to change a value we will get a FrozenInstanceError raised.

1
2
3
4
5
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.

1
2
3
4
from dataclasses import dataclass, asdict

the_user = asdict(user_one)
print(the_user)

Research

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.

See Also

Buy Me A Coffee