In many software projects, you'll often encounter the need to track tasks or to-do items, and these tasks can have various statuses like "To Do," "In Progress," or "Done." To handle this, we can define a custom data type called Task
that encapsulates both the task's description and its status. Here's the example code with explanations:
from enum import Enum
from typing import NamedTuple
# Define an enumeration for task statuses
class TaskStatus(Enum):
TODO = 1
IN_PROGRESS = 2
DONE = 3
# Define a custom data type for tasks using a NamedTuple
class Task(NamedTuple):
description: str
status: TaskStatus
Let's break down the code step by step:
TaskStatus
to represent the possible statuses a task can have: "TODO," "IN_PROGRESS," and "DONE." Enums are a great way to ensure that only valid status values are used.NamedTuple
to define our custom data type called Task
. A NamedTuple
is similar to a regular tuple, but it has named fields, making it more self-documenting and easier to work with.
description
: This field stores a string representing the task's description.status
: This field stores a value from the TaskStatus
enumeration, indicating the current status of the task.With this custom data type in place, you can create and work with tasks in a more structured way. Here's how you might use the Task
data type:
# Creating tasks
task1 = Task(description="Write documentation", status=TaskStatus.TODO)
task2 = Task(description="Implement feature", status=TaskStatus.IN_PROGRESS)
task3 = Task(description="Review code", status=TaskStatus.DONE)
# Accessing task properties
print(task1.description) # Output: "Write documentation"
print(task2.status) # Output: TaskStatus.IN_PROGRESS
# Checking task status
if task3.status == TaskStatus.DONE:
print("Task is done!")
# Iterating through tasks
tasks = [task1, task2, task3]
for task in tasks:
print(f"{task.description} - Status: {task.status.name}")
By using this custom data type, you enhance the clarity of your code, make it less error-prone, and enable better communication about the structure and meaning of tasks within your codebase.