0%

Structured Output · practice

Name the Type of Each Value

At the end of Lesson 2, a reply with "answer_index": "abc" passed every check, because the checks never said what type each value should have. Before you can have types checked, you need a way to write them down. Python has one: type hints.

A hint names a type

A hint goes after a name, with a colon:

name: str = "Ana"
count: int = 3
scores: list[int] = [90, 72, 85]
ages: dict = {"Ana": 31}
print(name, count, scores, ages)

name: str = "Ana" reads “name is a string, and its value is "Ana"”. list[int] means a list whose items are integers, and list[str] a list of strings. A plain dict says the value is a dictionary without saying more about its keys and values; list[dict] is a list of dictionaries. Those are all the forms this course needs.

Functions take hints too. Each parameter gets one after its name, and the result gets one after ->, between the closing parenthesis and the colon:

def describe(name: str, count: int) -> str:
    return f"{name} has {count} items"


print(describe("scores", 3))

Python does not check hints

A hint is information for people and for tools. Python stores it and otherwise ignores it when the code runs:

def double(number: int) -> int:
    return number * 2


print(double("ab"))

The hint says number is an integer, Python calls the function with a string anyway, and "ab" * 2 is "abab". No error, no warning. Code editors and checking tools such as mypy read hints and can warn you about a call like this before you run anything, and a person reading def double(number: int) -> int: knows what to pass without reading the body. That is what hints are for here: they say what a function expects and returns.

Add hints to your two functions

Give Lesson 2’s functions their hints. Only the def lines change:

def quiz_request(note_text: str) -> dict:
def read_quiz_json(text: str) -> list[dict]:

quiz_request takes the note as text and returns a request body, a dictionary. read_quiz_json takes the reply text and returns the list of question dictionaries.

Run it

Run python structured.py. Since Lesson 2, the demonstration has also called read_quiz_json(42), a number where the hint now says text:

read_quiz_json given a number instead of text:
  TypeError: the JSON object must be str, bytes or bytearray, not int
A QuizQuestion from sample_question:
Run stopped at the next function to build: sample_question is built in Lesson 4.

The output is the same before and after you add the hints, and that is the point. The error does not come from the hint. It comes from json.loads, the first line of the body, which cannot decode a number. Without that line, the number would have traveled farther before anything failed.

Hints inside a class

One more form, because Lesson 4 reads it. Inside a class body, a line can have a name and a hint and no value at all:

question: str
choices: list[str]
answer_index: int

Written at the top of a file, as here, these lines do nothing you can see. Inside a pydantic model, the kind of class Lesson 4 reads, each one declares a field: a named value that every object of that model holds, with the type it should have. In Lesson 4 you will see exactly these three lines inside a class that describes one quiz question, and there, because pydantic reads the hints, they do get checked.

A function is defined as def double(number: int) -> int: and returns number * 2. What does double("ab") do?

Which hint describes what read_quiz_json returns?

Task

In structured.py, add type hints to the two functions from Lesson 2. Change only their def lines:

  • quiz_request(note_text): note_text is a str, and the function returns a dict.

  • read_quiz_json(text): text is a str, and the function returns a list[dict].

Keep the bodies as they are: hints change nothing when the code runs. Run python structured.py to see that a value that breaks a hint fails in the code, not in the hint, then check your work.