build a dataclass in python

In Python, dataclasses are used to create classes that are primarily used to store data. These classes are similar to normal classes, but they provide several powerful features for free such as automatic creation of __init__, __repr__, and other methods, default values for attributes, typing, and more.

To create a dataclass in Python, you must first import the dataclass decorator from the dataclasses module. Here's an example of how to create a simple data class:

main.py
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
    email: str = None
109 chars
8 lines

In this example, we created a Person dataclass with three attributes: name, age, and email. We used the dataclass decorator and specified the types of each attribute. We also set a default value for email.

We can now create instances of the Person class and access their attributes:

main.py
person = Person("John", 30)
print(person.name)  # Output: John
print(person.age)  # Output: 30
print(person.email)  # Output: None
131 chars
5 lines

As you can see, creating a dataclass is very simple and can save you a lot of time and boilerplate code.

gistlibby LogSnag