from pathlib import Pathp = Path('expenses.json')print(p.name)
Output
expenses.json
Your output
Example: ex-datetime
Using datetime to format a date string.
python
from datetime import datetimed = datetime(2026, 7, 29)print(d.strftime('%Y-%m-%d'))
Output
2026-07-29
Your output
BugHunt / Predict the Output: The following code tries to serialize an Expense dataclass directly to JSON, but it crashes. What exception do you think it raises?
Click here to make your guess
It raises a TypeError! Custom objects like dataclasses cannot be directly serialized by JSON. You must convert it to a dictionary first using dataclasses.asdict().
Check yourself
You try to json.dump() a dataclass instance and get a TypeError. Why?
Reveal answer
JSON only handles strings, numbers, booleans, lists and dicts โ convert to a dict first โ json only knows the basic JSON types. Use dataclasses.asdict(obj) (or a custom default=) to turn the object into a dict first.
You wrote a TestCase class but running the file prints nothing. What is missing?
Reveal answer
unittest.main(), or running it through a test runner โ Defining tests does not run them. unittest.main() (or python -m unittest) discovers and executes them.
Does @dataclass enforce the type hints you write on its fields?
Reveal answer
No โ hints define the structure, but nothing is checked at runtime โ Type hints are used to generate __init__ and friends, not to validate. Passing the wrong type succeeds silently unless you add checks.
What is the difference between json.load and json.loads?
Reveal answer
load reads from a file object; loads parses a string โ The trailing s means string. json.load(f) takes an open file; json.loads(text) takes a str.
Challenges
Challenge 1 +20 XP
Create an Expense dataclass with amount (float), category (str), and date (str). Instantiate one for a 15.50 'Food' expense on '2026-07-29' and print it.
python
Test 1 โ expects "Expense(amount=15.5, category='Food', date='2026-07-29')"
Need a hint? (โ25% XP)
Use @dataclass and define the fields with their types. Then create the object and print it.
BugHunt: The following code tries to serialize an Expense dataclass directly to JSON, but it crashes. Fix it by converting the dataclass to a dictionary using asdict().
python
Test 1 โ expects "{\"amount\": 15.5, \"category\": \"Food\"}"
Need a hint? (โ25% XP)
Use the asdict() function from the dataclasses module.