# 第 2-9 课完整示例:任务业务功能模块 # # 本模块使用字典表示任务。面向对象的“类”会在第三阶段学习。 from functools import wraps def log_call(func): @wraps(func) def wrapper(*args, **kwargs): print(f"正在执行:{func.__name__}") return func(*args, **kwargs) return wrapper def get_next_task_id(tasks: list[dict[str, object]]) -> int: """根据已有任务计算下一个可用编号。""" if not tasks: return 1 # 列表推导式只取出编号;max() 找到其中最大的编号。 task_ids = [int(task["id"]) for task in tasks] return max(task_ids) + 1 @log_call def add_task(tasks, title: str, priority: str) -> dict[str, object]: """创建一条未完成任务,添加到列表并返回这条新任务。""" cleaned_title = title.strip() if not cleaned_title: raise ValueError("任务标题不能为空。") task = { "id": get_next_task_id(tasks), "title": cleaned_title, "priority": priority, "completed": False, } tasks.append(task) return task @log_call def complete_task(tasks: list[dict[str, object]], task_id: int) -> bool: """按编号把任务标记为完成;找到任务返回 True,否则返回 False。""" for task in tasks: if task["id"] == task_id: task["completed"] = True return True return False def generate_pending_tasks(tasks: list[dict[str, object]]): """逐条生成未完成任务,不预先创建新的完整列表。""" for task in tasks: if not task["completed"]: yield task def build_task_report(tasks: list[dict[str, object]]) -> dict[str, object]: """汇总全部、已完成和未完成任务数量。""" completed_tasks = [task for task in tasks if task["completed"]] return { "total": len(tasks), "completed": len(completed_tasks), "pending": len(tasks) - len(completed_tasks), }