Need a small model for a task’s title, description, and urgency? A named tuple holds those distinct values in an immutable, tuple-like object. Its field names make access clearer than positional indexing, without requiring a hand-written class. section 3.3 section 3.3.1 section 3.3.2
Create and read a task
from collections import namedtuple Task = namedtuple('Task', 'title desc urgency') task = Task('Laundry', 'Wash clothes', 3) print(task.title) print(task) # Output: # Laundry # Task(title='Laundry', desc='Wash clothes', urgency=3) The factory function creates the Task class; calling that class creates a task. Fields can also be supplied to namedtuple as a comma-separated string or a list of strings. Give the class a descriptive, uppercase-camel-case name. section 3.3.2
Choose a named tuple when the model mainly holds data for reading. A list permits changes; an ordinary tuple lacks descriptive field access; a dictionary exposes names as keys but requires key lookups. Keep the one-line class definition visible, such as near the top of its module. Because the resulting object is immutable, changing an urgency value requires a new object rather than assigning to the existing field. section 3.3.1 section 3.3.3 section 3.3.4
for task_text in task_data.split('\n'): #1
title, desc, urgency = task_text.split(',') #2
task_nt = Task(title, desc, int(urgency))
print(f"--> {task_nt}")
# output the following lines
--> Task(title='Laundry', desc='Wash clothes', urgency=3)
--> Task(title='Homework', desc='Physics + Math', urgency=5)
--> Task(title='Museum', desc='Epyptian things', urgency=2)
A parsing loop splits each incoming task record, converts urgency to an integer, and constructs a Task. The displayed output shows the field names alongside their values. section 3.3.2
The same lightweight model can package latitude and longitude as one function return value. Remember that tuple behavior still matters: when serialized to JSON, a named tuple becomes an array, not an object keyed by its field names. section 6.2.5 section 9.3.6


