Exercise: Comprehensions, Exceptions, and Dataclasses
Part 1: For Loops Into Comprehensions
Rewrite each for loop below as a list comprehension.
Build a list of slugs from project names:
Python
project_names = ["Payments API", "Developer Portal", "Ops Console"]
slugs = []
for name in project_names:
slugs.append(name.lower().replace(" ", "-"))
Build a list of titles for tasks that aren't done:
Python
tasks = [
{"title": "ship docs", "done": False},
{"title": "cut release", "done": True},
{"title": "announce launch", "done": False},
]
open_titles = []
for task in tasks:
if not task["done"]:
open_titles.append(task["title"])
Part 2: Raise and Catch an Exception
Write validate_project_name(name) that strips the input and raises ValueError("Project name cannot be blank.") if the result is empty. Otherwise it returns the cleaned name.
Then call it with " " inside a try/except block and print the caught exception's message.
Part 3: A Simple Dataclass
Define a Project dataclass with three fields:
name: strslug: strarchived: bool = False
Create a Project instance, print it, and confirm archived defaults to False.
Solution
Python
from dataclasses import dataclass
project_names = ["Payments API", "Developer Portal", "Ops Console"]
slugs = [name.lower().replace(" ", "-") for name in project_names]
tasks = [
{"title": "ship docs", "done": False},
{"title": "cut release", "done": True},
{"title": "announce launch", "done": False},
]
open_titles = [task["title"] for task in tasks if not task["done"]]
def validate_project_name(name: str) -> str:
cleaned = name.strip()
if not cleaned:
raise ValueError("Project name cannot be blank.")
return cleaned
@dataclass
class Project:
name: str
slug: str
archived: bool = False
if __name__ == "__main__":
print(slugs)
print(open_titles)
try:
validate_project_name(" ")
except ValueError as e:
print(f"Validation failed: {e}")
payments = Project(name="Payments API", slug="payments-api")
print(payments)
print(payments.archived)
Success
If the script prints the two comprehension results, the ValueError message, the Project repr, and False for archived, you've practiced enough of the chapter's tools to move on.