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
# import package
from dataclasses import dataclass
# make a dataclass with decorator
@dataclass
class DataClassGFG:
Job: str
Salary: float
# make an object with values required by dataclass
DataClassObject = DataClassGFG("Author",50000.00)
# view dataclass object
print(DataClassObject)
Output:
DataClassGFG(Job='Author', Salary=50000.0)
2. Using make_dataclass():
Example:
Python3
# import package
from dataclasses import make_dataclass
# make a dataclass with make_dataclass
DataClassGFG = make_dataclass("DataClassGFG",["Job","Salary"])
# make an object with values required by dataclass
DataClassObject = DataClassGFG("Author",50000.00)
# view dataclass object
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
# import package
from collections import namedtuple
# make a dataclass with namedtuple
DataClassGFG = namedtuple("DataClassGFG",["Job","Salary"])
# make an object with values required by dataclass
DataClassObject = DataClassGFG("Author",50000.00)
# view dataclass object
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
# import package
from dataclasses import dataclass
# make a dataclass with decorator
@dataclass(frozen=True)
class DataClassGFG:
Job: str
Salary: float
# make an object with values required by dataclass
DataClassObject = DataClassGFG("Author",50000.00)
# view dataclass object
print(DataClassObject)
# check immutable nature of class
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
# import package
from dataclasses import dataclass
from typing import List
# make a dataclass with decorator
@dataclass
class DataClassGFG:
Job: str
Salary: float
@dataclass
class GFGJobs:
Jobs: List[DataClassGFG]
# make objects with values required by dataclass
DataClassObject1 = DataClassGFG("Author",50000.00)
DataClassObject2 = DataClassGFG("Writer",40000.00)
# view dataclass objects
print(DataClassObject1)
print(DataClassObject2)
# make an object of another dataclass
GFGJobsObject = GFGJobs([DataClassObject1,DataClassObject2])
# view dataclass object
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
# import package
from dataclasses import dataclass
# make a dataclass with decorator
@dataclass
class DataClassGFG:
Job: str
Salary: float
@dataclass
class SlotClassGFG:
__slots__ = ["Job","Salary"]
Job: str
Salary: float
# make objects with values required by dataclass
DataClassObject1 = DataClassGFG("Author",50000.00)
DataClassObject2 = SlotClassGFG("Writer",40000.00)
# view dataclass objects
print(DataClassObject1)
print(DataClassObject2)
# view dataclass object slot
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
# import package
from dataclasses import dataclass
# make a dataclass with decorator
@dataclass
class DataClassGFG:
Job: str
Salary: float
@dataclass
class SubDataClassGFG(DataClassGFG):
Standard: str = "Top"
Salary: float = 100000.00
# make objects with values required by dataclass
DataClassObject1 = DataClassGFG("Author",100000.00)
DataClassObject2 = DataClassGFG("Author",50000.00)
# view dataclass objects
print(DataClassObject1)
print(DataClassObject2)
# make object with values required by subdataclass
SubDataClassObject = SubDataClassGFG("Author")
# view subdataclass object
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 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. Python3 1== from dataclasses import data
2 min read
Data Classes in Python | Set 2 (Decorator Parameters) Prerequisite: Data Classes in Python | Set 1 In this post, we will discuss how to modify the default constructor which dataclass module virtually makes for us. dataclass() decorator - @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) By changing t
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
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
Metaprogramming with Metaclasses in Python Metaprogramming in Python lets us write code that can modify or generate other code at runtime. One of the key tools for achieving this is metaclasses, which allow us to control the creation and behavior of classes.What Are Metaclasses?Metaclasses are classes that define how other classes are create
7 min read