Sling Academy
Home/Python/Introduction to Dataclass in Python

Introduction to Dataclass in Python

Last updated: March 01, 2023

This article is about the basics of dataclass in modern Python.

Overview

Dataclasses are a relatively new feature added to Python 3.7 that simplifies the process of creating classes to model and store data. They are essentially a shortcut to defining classes that have a specific set of attributes or properties. They automatically add the __init__(), __repr__(), and other common methods, therefore significantly reducing the amount of boilerplate code that is needed when defining classes.

This is a minimum example of defining a dataclass:

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

When we decorate the class with @dataclass, Python automatically generates an __init__() method that takes 2 arguments: name and price. It also generates a __repr__() method that returns a string representation of the object:

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

product = Product('Apple', 1.99)
print(product.__repr__())

Output:

Product(name='Apple', price=1.99)

More Examples

I believe that examples will help you learn and grasp the knowledge better than boring words. Below are some real-world examples of implementing dataclasses in Python.

A simple class to present a book

The code:

from dataclasses import dataclass

@dataclass
class Book:
    title: str
    author: str
    pages: int
    price: float


book = Book("Sling Academy Ruins", "Blazing Bull", 1208, 9.99)
print(book)

Output:

Book(title='Sling Academy Ruins', author='Blazing Bull', pages=1208, price=9.99)

A class to present a rectangle

The code:

from dataclasses import dataclass

@dataclass
class Rectangle:
    width: float
    height: float

    # this method calculates the area of the rectangle
    def area(self):
        return self.width * self.height

    # this method calculates the perimeter of the rectangle
    def perimeter(self):
        return 2 * (self.width + self.height)


# Try it
rectangle = Rectangle(3, 4) 
print(rectangle.area())
print(rectangle.perimeter())

Output:

12
14

The above is the first step to help you familiarize yourself with dataclasses. In the next articles, we will explore more advanced things.

Next Article: Python: Defining Fields in Dataclass

Series: Working with Dataclasses in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots