The Ultimate Guide to Data Classes in Python 3.7
Last Updated :
11 Oct, 2020
This article discusses data classes in Python 3.7 and provides an introductory guide for data classes in Python 3.7 and above.
Data Class is a new concept introduced in Python 3.7 version. You can use data classes not only as a knowledge container but also to write boiler-plate code for you and simplify the process of creating classes since it comes with some methods implemented for free. A data class could also be considered as a category typically containing data, but they aren’t limited to that.
Basic Data Classes
The following ways show how a basic data class can be created:
1. Using decorator: They are created using the new @dataclass decorator.
Example:
Python3
from dataclasses import dataclass
@dataclass
class DataClassGFG:
Job: str
Salary: float
DataClassObject = DataClassGFG( "Author" , 50000.00 )
print (DataClassObject)
|
Output:
DataClassGFG(Job=’Author’, Salary=50000.0)
2. Using make_dataclass():
Example:
Python3
from dataclasses import make_dataclass
DataClassGFG = make_dataclass( "DataClassGFG" ,[ "Job" , "Salary" ])
DataClassObject = DataClassGFG( "Author" , 50000.00 )
print (DataClassObject)
|
Output:
DataClassGFG(Job=’Author’, Salary=50000.0)
3. Using namedtuple: Using namedtuple() method from collections. The is just similar to make_dataclass().
Example:
Python3
from collections import namedtuple
DataClassGFG = namedtuple( "DataClassGFG" ,[ "Job" , "Salary" ])
DataClassObject = DataClassGFG( "Author" , 50000.00 )
print (DataClassObject)
|
Output:
DataClassGFG(Job=’Author’, Salary=50000.0)
Immutable Data Classes
One of the defining features of the namedtuple we saw earlier is that it’s immutable i.e., the value of its fields may never change. For several sorts of data classes, this is often an excellent idea to create an immutable class and to achieve this just simply set frozen=True once you create it.
Example:
Python3
from dataclasses import dataclass
@dataclass (frozen = True )
class DataClassGFG:
Job: str
Salary: float
DataClassObject = DataClassGFG( "Author" , 50000.00 )
print (DataClassObject)
DataClassObject.Job = "Writer"
|
Output:
DataClassGFG(Job=’Author’, Salary=50000.0)
Traceback (most recent call last):
File “main.py”, line 17, in <module>
DataClassObject.Job = “Writer”
File “<string>”, line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field ‘Job’
Flexible Data Classes
We already discussed some methods to make dataclasses and now we’ll study some more advanced features like parameters to a @dataclass decorator. Adding parameters to a dataclass provides us with more control when creating a data class.
Example:
Python3
from dataclasses import dataclass
from typing import List
@dataclass
class DataClassGFG:
Job: str
Salary: float
@dataclass
class GFGJobs:
Jobs: List [DataClassGFG]
DataClassObject1 = DataClassGFG( "Author" , 50000.00 )
DataClassObject2 = DataClassGFG( "Writer" , 40000.00 )
print (DataClassObject1)
print (DataClassObject2)
GFGJobsObject = GFGJobs([DataClassObject1,DataClassObject2])
print (GFGJobsObject)
|
Output:
DataClassGFG(Job=’Author’, Salary=50000.0)
DataClassGFG(Job=’Writer’, Salary=40000.0)
GFGJobs(Jobs=[DataClassGFG(Job=’Author’, Salary=50000.0), DataClassGFG(Job=’Writer’, Salary=40000.0)])
Optimizing Data Classes
For optimizing the data classes we use slots. Slots are often used to make classes faster and use less memory. Data classes don’t have any explicit syntax for working with slots, but the traditional way of making slots works for data classes also.
Example:
Python3
from dataclasses import dataclass
@dataclass
class DataClassGFG:
Job: str
Salary: float
@dataclass
class SlotClassGFG:
__slots__ = [ "Job" , "Salary" ]
Job: str
Salary: float
DataClassObject1 = DataClassGFG( "Author" , 50000.00 )
DataClassObject2 = SlotClassGFG( "Writer" , 40000.00 )
print (DataClassObject1)
print (DataClassObject2)
print (DataClassObject2.__slots__)
|
Output:
DataClassGFG(Job=’Author’, Salary=50000.0)
SlotClassGFG(Job=’Writer’, Salary=40000.0)
[‘Job’, ‘Salary’]
Inheritance
We can simply use the concept of inheritance by creating sub data class of a data class.
Example:
Python3
from dataclasses import dataclass
@dataclass
class DataClassGFG:
Job: str
Salary: float
@dataclass
class SubDataClassGFG(DataClassGFG):
Standard: str = "Top"
Salary: float = 100000.00
DataClassObject1 = DataClassGFG( "Author" , 100000.00 )
DataClassObject2 = DataClassGFG( "Author" , 50000.00 )
print (DataClassObject1)
print (DataClassObject2)
SubDataClassObject = SubDataClassGFG( "Author" )
print (SubDataClassObject)
|
Output:
DataClassGFG(Job=’Author’, Salary=100000.0)
DataClassGFG(Job=’Author’, Salary=50000.0)
SubDataClassGFG(Job=’Author’, Salary=100000.0, Standard=’Top’)
Similar Reads
Data Classes in Python | Set 3 (dataclass fields)
Prerequisite: Data Classes in Python Set 1 | Set 2 In this post we will discuss how to modify certain properties of the attributes of DataClass object, without explicitly writing code for it using field function. field() function - dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=
4 min read
Data Classes in Python | Set 4 (Inheritance)
Prerequisites: Inheritance In Python, Data Classes in Python | Set 3 In this post, we will discuss how DataClasses behave when inherited. Though they make their own constructors, DataClasses behave pretty much the same way as normal classes do when inherited. from dataclasses import dataclass @datac
2 min read
How To Convert Data Types in Python 3?
Type Conversion is also known as typecasting, is an important feature in Python that allows developers to convert a variable of one type into another. In Python 3, type conversion can be done both explicitly (manual conversion) and implicitly (automatic conversion by Python). Table of Content Types
4 min read
Data Classes in Python | An Introduction
dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.DataClasses in widely used Python3.6 Although the module was introduced
3 min read
Data Classes in Python | Set 6 (interconversion to and from other datatypes)
Prerequisite: Data Classes in Python | Set 5 In the last post of DataClass series, we will discuss how to get values of a DataClass object into a dictionary or tuple pairs and how to create a DataClass in a different way - from values, instead of defining it directly. asdict() function - dataclasses
2 min read
Comparing Old-Style and New-Style Classes in Python
In Python, the difference between old-style and new-style classes is based on the inheritance from the built-in object class. This distinction was introduced in Python 2.x and was fully adopted in Python 3.x, where all classes are new-style classes. In this article, we will see the difference betwee
4 min read
Best Python IDEs For Data Science in 2024
It is easier for anyone to take a decision if they have any existing data regarding that, and as Data-driven decision-making is increasing in companies, the demand for efficient and powerful Python IDEs is increasing for Data Science. And it is very important to select the correct Python IDE for Dat
6 min read
Classifying Data With Pandas In Python
Pandas is a widely used Python library renowned for its prowess in data manipulation and analysis. Its core data structures, such as DataFrame and Series, provide a powerful and user-friendly interface for handling structured data. This makes Pandas an indispensable tool for tasks like classifying o
5 min read
Latest Update on Python 4.0
Python remains one of the most popular programming languages in 2024, known for its simplicity, versatility, and extensive ecosystem. As Python continues to evolve with regular updates to the Python 3.x series, speculation about the potential release of Python 4.0 has surfaced. However, recent state
6 min read
How To Read .Data Files In Python?
Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
4 min read