<aside> <img src="/icons/row_gray.svg" alt="/icons/row_gray.svg" width="40px" /> Page Contents
</aside>
Featured
NamedTuple
is a convenient and versatile feature in Python's typing module that allows you to define simple classes with named fields, similar to tuples or records. It provides a structured way to create data containers with named attributes, while still maintaining immutability. This guide will cover various use cases of NamedTuple
and provide walkthroughs for each scenario.
NamedTuple is a subclass of the built-in tuple type, but it adds named fields. It can be imported from the typing
module:
from typing import NamedTuple
NamedTuple
can be used to create data classes that are lightweight, memory-efficient, and provide attribute-based access like regular classes. It's particularly useful when you need to define a simple data structure without the complexity of a full class definition.
Here's how you define a NamedTuple:
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float
You can create instances of this Point NamedTuple just like you would with regular classes:
p = Point(1.0, 2.0)
print(p.x, p.y) # Output: 1.0 2.0
Data Container
NamedTuple
can be used to define simple data containers, similar to records in other programming languages.
class Person(NamedTuple):
name: str
age: int
person = Person(name="Alice", age=30)
print(person.name, person.age) # Output: Alice 30
Configuration Settings
You can use NamedTuple
to define configurations for your applications.
class AppConfig(NamedTuple):
app_name: str
debug_mode: bool
config = AppConfig(app_name="MyApp", debug_mode=True)
print(config.app_name, config.debug_mode) # Output: MyApp True