Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
Python Land
  • Python Tutorial
  • Shop
  • Blog
  • Login / Register
  • Contact
0
Home » Tips & Tricks » Python Data Class: A Better Way to Store Data
python data processing

Python Data Class: A Better Way to Store Data

October 7, 2024

A Python data class is a regular Python class that has the @dataclass decorator. It is specifically created to hold data. Since Python version 3.7, Python offers data classes through a built-in module that you can import, called dataclass. There are several advantages over regular Python classes, which we’ll explore in this article. We’ll also look at example code and some common operations you might want to perform with data classes.

Table of Contents

  • 1 The advantage of using data classes
  • 2 Python data class example
  • 3 Default values
  • 4 Converting a data class to JSON
  • 5 Keep learning

The advantage of using data classes

Why should you use a data class instead of a regular Python class? First, let’s look at some of the advantages a Python data class has to offer.

Requires a minimal amount of code

The @dataclass decorator adds a lot of functionality to a class without adding any visible code. This makes your data class very compact while still offering many useful features. All you need to do is define the fields to hold your data. You don’t need to define any functions.

Comparison

Instances of Python data classes can be compared with == because the so-called dunder method __eq__ is implemented automatically. In general, we can compare any Python object that implements this special method to other objects of the same type.

Printing a data class

Similarly, because __repr__ is implemented, you can print data classes and get a nice representation of it. This is especially useful for debugging.

Data classes require type hints

Data classes are built around the new(ish) type system Python offers. Using type hints reduces the chances of bugs and unexpected behavior in your code. You essentially declare the data type that should be stored in a variable.

Python data class example

Here’s an example of a data class at work:

from dataclasses import dataclass

@dataclass
class Card:
    rank: str
    suit: str
    
card1 = Card("Q", "hearts")
card2 = Card("Q", "hearts")

print(card1 == card2)
# True

print(card1.rank)
# 'Q'

print(card1)
Card(rank='Q', suit='hearts')

Default values

A data class can have default values. Assigning default values is as simple as assigning a value to a variable. For example, to make our Card class have a default value of Queen of Hearts, we can do as follows:

from dataclasses import dataclass

@dataclass
class Card:
    rank: str = 'Q'
    suit: str = 'hearts'

Converting a data class to JSON

A common use case is to convert your nicely structured data class to JSON. E.g., if you want to export the data to a database, or send it to the browser. The bad news here: there’s no built-in way to convert a data class to JSON. At least not in such a way that it can comfortably export all kinds of data types inside your class (like date objects).

The good news is, that there is a Python package called dataclasses-json that simplifies the task. However, it requires an extra decorator. You’ll need to install the package with the pip install command or something like Pipenv, preferably inside a virtual environment. For example:

$ pip install dataclasses-json

Here’s an example of how you can use the package:

from dataclasses import dataclass
from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class Card:
    rank: str = 'Q'
    suit: str = 'hearts'

card = Card()
print(card.to_json())

This results in the following output:

{"rank": "Q", "suit": "hearts"}

Another method is to use Python inheritance and inherit from the JSONEncoder class to create your own custom encoder. The advantage is that you don’t need to install an external package. You can learn how to do this in this blog post.

Keep learning

  • The Python attrs package has an advanced version of the native Python data class
  • The official documentation on Python.org
  • How to return multiple values in Python

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

  • Sale Product on sale
    The Python Course for Beginners
    Beginners Python Course (2024)
    € 59.00 Original price was: € 59.00.€ 39.00Current price is: € 39.00.
  • Sale Product on sale
    Computer Fundamentals
    Files, Folders, And The Command Line (2024)
    € 39.00 Original price was: € 39.00.€ 19.00Current price is: € 19.00.
  • Sale Product on sale
    Modules, Packages, And Virtual Environments (2024)
    Modules, Packages, And Virtual Environments (2024)
    € 59.00 Original price was: € 59.00.€ 39.00Current price is: € 39.00.

1 thought on “Python Data Class: A Better Way to Store Data”

  1. fmalina
    April 25, 2022 at 10:49 am

    There’s actually a simple built in way to convert a dataclass to JSON:

    
    >>> import json
    >>> json.dumps(card1.__dict__)
    '{"rank": "Q", "suit": "hearts"}'
    Code language: Python (python)

    And even if your data class has attributes that are not JSON serializable by default

    
    >>> import datetime
    >>> @dataclass
    ... class Card:
    ...     rank: str
    ...     suit: str
    ...     last_played: datetime.datetime
    ... 
    >>> card1 = Card("Q", "hearts", datetime.datetime.now())
    >>> json.dumps(card1.__dict__)
    Traceback ... TypeError: Object of type datetime is not JSON serializable
    >>> def dt_serializer(o):
    ...     if isinstance(o, datetime.datetime):
    ...         return o.__str__()
    ... 
    >>> json.dumps(card1.__dict__, default=dt_serializer)
    '{"rank": "Q", "suit": "hearts", "last_played": "2022-04-25 10:29:01.833211"}'
    Code language: Python (python)

    Also interesting to look at is:

    
    >>> card1.__annotations__
    {'sent': , 'suit': , 'rank': }
    Code language: Python (python)
    Log in to Reply

Leave a Comment Cancel reply

You must be logged in to post a comment.

Subscribe to my newsletter for Python news, tips, and tricks!

Footer subscribe

  • Home
  • Python Courses
  • Privacy Policy
  • About Us
  • Contact us
©2025 Python Land - All rights reserved
Python Land is not affiliated with Python.org or the Python Software Foundation
  • Free Tutorial
    • Install Python
      • Online Python Interpreter
      • How To Open Python on Windows, Mac, Linux
    • Introduction to Python
      • The Python REPL
      • Python Variable
      • Python String
      • Python Print function
      • Python Booleans
      • For-loop and While-loop
      • Python Functions
      • Your First Python Program
      • Python Comments
    • Creating Python Programs
      • The Best Python IDE
      • Installing VSCode
      • VSCode Python Extensions
      • VSCode GUI Tour
      • Python in VSCode: Running and Debugging
    • Classes and Objects in Python
      • Python Constructor
      • Python Inheritance
    • Structure Your Project
      • Python Modules And Importing
      • Python Packages
    • Python Data Types
      • Python Integer
      • Python Float
      • Python Tuple
      • Python List
      • Python Set
      • Python Dictionary
    • Language Deep Dives
      • Python Try Except (Exceptions)
      • Python Functions: Advanced Concepts
      • List Comprehension
      • Python Iterator
      • Python Range
      • Python Docstrings
      • Python pass (Do Nothing)
    • Interaction with the OS
      • Python Read And Write File
      • Python Subprocess: Run External Commands
    • Venvs / Package Management
      • Working With Python’s venv
      • Pip install: the Python package manager
      • Python Poetry: Package and venv Management Made Easy
      • Python Pipenv: Another Package Manager
      • Pipx: Safely Install Packages Globally
    • Python Concurrency
      • The Python GIL (Global Interpreter Lock)
      • Setting the Baseline
      • Python Threading
      • Python Multiprocessing
    • Data Processing with Python
      • Working With JSON
        • JMESPath Python: JSON Query Language
      • Python YAML: How to Load, Read, and Write YAML
      • Python CSV: Read And Write CSV Files
    • Migrating From Python 2 to 3
      • Check Python Version On The Command-Line
      • How to Migrate To Python 3
      • Python 3 Advantages
    • Using The Unix Shell
      • Basic Linux Commands
      • Bash Scripts
      • Using the Find Command in Linux
      • Unix Pipes
      • Process and Highlight JSON with jq
      • Using the Bash History
      • Bash Multiprocessing
    • Deployment
      • PyInstaller: Create An Executable From Python Code
      • How To Use Docker To Containerize Your Python Project
      • Automatically Build and Deploy Your Python Application with CI/CD
      • Guerrilla Scale Your Web Application
    • Data Science
      • Jupyter Notebook
      • NumPy: Getting Started Tutorial
    • Python Learning Resources
  • Python Courses
  • Blog
  • Login / Register