Need to create, display, and save individual tasks? Model each one as a Task instance. Its attributes hold a task ID, title, description, urgency, status, and completion note; its methods handle creation and persistence. section 14.2.1 section 14.2.3
Find a task by urgency
A small Task class is enough when the immediate job is finding a row to highlight: class Task: def __init__(self, title, urgency): self.title = title self.urgency = urgency tasks = [Task("Laundry", 3), Task("Museum", 4), Task("Homework", 5), Task("Ticket", 2)] needed_task_index = None for task_i in range(len(tasks)): if tasks[task_i].urgency == 5: needed_task_index = task_i break print(needed_task_index) # 2 Search the attribute because the desired object is not known in advance. A newly constructed Task with the same values is still a distinct object; do not assume tasks.index(Task("Homework", 5)) finds the existing one. section 4.3.4 section 4.3.6
For an application with stored tasks, give the class methods that match the work:
- Initialize the full set of task attributes. A class method can turn form entries into a Task, using a static utility method to generate its ID. section 14.2.3
- Save an instance, load tasks matching filters, and update or delete a stored record. The shown CSV save path appends a formatted row; the shown SQLite branches are placeholders. section 14.2.3
- Provide __str__ for a readable task display and __repr__ for a representation containing its attributes. section 14.2.3
Listing 14.2 Saving a record to the database
def save_to_db(self):
"""Save the record to the database
"""
if app_db == TaskierDBOption.DB_CSV.value:
with open(app_db, "a", newline="") as file:
csv_writer = csv.writer(file)
db_record = self._formatted_db_record()
csv_writer.writerow(db_record)
else:
# operations when the database is the SQLite3
pass
def _formatted_db_record(self):
db_record = (self.task_id, self.title, self.desc, self.urgency,
self.status.value, self.completion_note)
return db_record
The save method shows the division of labor: the instance formats its record, then a CSV writer appends it to the selected file. section 14.2.3
Keep this data model in a separate file and import it into the Streamlit interface. That keeps interface code easier to read and leaves the class available to another kind of app. section 14.4.8
