typing.NamedTuple – Improved Namedtuples

02 Sep, 2020
The NamedTuple class of the typing module added in Python 3.6 is the younger sibling of the namedtuple class in the collections module. The main difference being an updated syntax for defining new record types and added support for type hints. Like dictionaries, NamedTuples contain keys that are hashed to a particular value. But on the contrary, it supports both access from key-value and iteration, the functionality that dictionaries lack.
NamedTuple can be created using the following syntax:
class class_name(NamedTuple):
    field1: datatype
    field2: datatype
This is equivalent to:
class_name = collections.namedtuple('class_name', ['field1', 'field2'])
Example:
Python3
# importing the modulefrom typing import NamedTuple  # creating a classclass Website(NamedTuple):    name: str    url: str    rating: int  # creating a NamedTuplewebsite1 = Website('GeeksforGeeks',                   'geeksforgeeks.org',                   5)  # displaying the NamedTupleprint(website1)
Output:
Website(name='GeeksforGeeks', url='geeksforgeeks.org', rating=5)
Access by index: The attribute values of namedtuple() are ordered and can be accessed using the index number, unlike dictionaries that are not accessible by index.Access by keyname: Access by key name is also allowed as in dictionaries.using getattr(): This is yet another way to access the value by giving namedtuple and key-value as its argument.
Access by index: The attribute values of namedtuple() are ordered and can be accessed using the index number, unlike dictionaries that are not accessible by index.
Access by keyname: Access by key name is also allowed as in dictionaries.
using getattr(): This is yet another way to access the value by giving namedtuple and key-value as its argument.
Example:
Python3
# importing the modulefrom typing import NamedTuple  # creating a classclass Website(NamedTuple):    name: str    url: str    rating: int  # creating a NamedTuplewebsite1 = Website('GeeksforGeeks',                   'geeksforgeeks.org',                   5)  # accessing using indexprint("The name of the website is : ", end = "")print(website1[0])  # accessing using nameprint("The URL of the website is : ", end = "")print(website1.url)    # accessing using getattr() print("The rating of the website is : ", end = "")print(getattr(website1, 'rating'))
Output:
The name of the website is : GeeksforGeeks
The URL of the website is : geeksforgeeks.org
The rating of the website is : 5
The fields are immutable. So if we try to change the values, we get the attribute error:
Python3
# importing the modulefrom typing import NamedTuple  # creating a classclass Website(NamedTuple):    name: str    url: str    rating: int  # creating a NamedTuplewebsite1 = Website('GeeksforGeeks',                   'geeksforgeeks.org',                   5)  # changing the attribute valuewebsite1.name = "Google"
Output:
AttributeError: can't set attribute

Python-OOP
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list