How to use NamedTuple and Dataclass in Python?

We have all worked with classes and objects for more than once while coding. But have you ever wondered how to create a class other than the naive methods we have all been taught. Don’t worry in this article we are going to cover these alternate methods. There are two alternative ways to construct a class in Python. 

First, of all let’s create a class with the naive methods. Let’s create a class transaction, where each payment transaction has a sender, a receiver, date, and the amount. 

Example:

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

class Transaction:
      
    def __init__(self, amount, sender, receiver, date):
      self.amount = amount
      self.sender = sender
      self.receiver = receiver
      self.date = date

chevron_right


This is pretty straight forward but let’s be honest this is a lot of code for us lazy developers. Now, this is where NamedTuple comes in.

Using NamedTuple

Named Tuple is essentially an extension of the Python built-in tuple data type. Python’s tuple is a simple data structure for grouping objects with different types. Its defining feature is being immutable i.e an object whose state cannot be modified after it is created. 



We will start with the collections package. This package provides alternatives to Python’s general built-in types like dict, list, set, and tuple. Creating a NamedTuple object is as straightforward as creating the class. 
 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

import collections
  
Transaction = collections.namedtuple('Transaction',
                                     ['sender', 'amount',
                                      'receiver', 'date'])
  
# Creating object
record = Transaction(sender="Aryaman",
                     receiver="Ankur",
                     date="2020-06-18",
                     amount=1.0)
  
print(record)
print(record.receiver)

chevron_right


Output:

Transaction(sender=’Aryaman’, amount=1.0, receiver=’Ankur’, date=’2020-06-18′)

Ankur

 Using DataClass

DataClass may be a new feature introduced since Python 3.7. It is used as a decorator. What it does under the hood is implementing __init__, __repr__, etc for us.
 

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

from dataclasses import dataclass
  
  
@dataclass
class Transaction:
    sender: str
    receiver: str
    date: str
    amount: float
  
  
# Creating object
record = Transaction(sender="Aryaman",
                     receiver="Ankur",
                     date="2020-06-18",
                     amount=1.0)
  
print(record)
print(record.receiver)

chevron_right


Output:

Transaction(sender=’Aryaman’, receiver=’Ankur’, date=’2020-06-18′, amount=1.0)
Ankur

NamedTuple behaves like a tuple, while DataClass behaves more like a regular Python class because by default, the attributes are all mutable and they can only be accessed by name, not by index.
 




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.