0%

Structured Output · practice

Read a Pydantic Model

Lesson 3 ended with three bare lines, question: str, choices: list[str] and answer_index: int, and the promise that inside a class they declare fields. This lesson reads the class they belong to. It is in quiz_models.py, next to structured.py. Open it.

Read quiz_models.py line by line

from pydantic import BaseModel


class QuizQuestion(BaseModel):
    question: str
    choices: list[str]
    answer_index: int

from pydantic import BaseModel imports from pydantic, a widely used library for describing data and checking it. It is installed in your sandbox; at home it is pip install pydantic==2.14.2, the version requirements.txt names.

class QuizQuestion(BaseModel): starts a pydantic model called QuizQuestion. This course does not teach you to design classes. You copy this one line as a fixed form: the word class, the model’s name, (BaseModel) and a colon. It tells Python and pydantic that the indented lines below describe one kind of data. By convention, model names start with a capital letter and run words together, like QuizQuestion.

From here on the chapter uses ‘model’ in two senses: the language model that writes the reply, and a pydantic model such as QuizQuestion that describes data. Where it could be either, the text says which.

The three indented lines are the fields, in the form from Lesson 3. Every QuizQuestion holds a question that is a string, choices that is a list of strings, and an answer_index that is an integer. That is the same shape read_quiz_json checked in Lesson 2, written as types.

Below the class, quiz_models.py has one more line, QuizSet = None. It is a placeholder that you replace in Lesson 5.

Create one, and read its values

You call a model to create an object from it, the way you call int("7") to create an integer. Pass each field as a keyword argument:

from pydantic import BaseModel


class QuizQuestion(BaseModel):
    question: str
    choices: list[str]
    answer_index: int


question = QuizQuestion(question="Which brackets make a list?", choices=["()", "[]", "{}"], answer_index=1)
print(question.question)
print(question.choices[question.answer_index])
print(question.model_dump())

question.choices reads the value of the choices field. A name, a dot and a field name reads a value stored on an object. You have done this before without the name: in Python in Practice you read exc.response.status_code off a requests error, and in Chapter 3 you read error.partial_text off a StreamBroken. Here you read a field the same way. The value is an ordinary list, so question.choices[question.answer_index] indexes it as any list.

model_dump() gives the object’s values back as a dictionary:

Which brackets make a list?
[]
{'question': 'Which brackets make a list?', 'choices': ['()', '[]', '{}'], 'answer_index': 1}

Compared with the dictionary read_quiz_json returns, a model makes its shape visible in one place, and its values are read with a dot instead of square brackets and a key in quotes. It also checks types, which Lesson 6 puts to work: creating a QuizQuestion with answer_index="first" raises an error instead of creating the object.

Build sample_question and correct_choice

sample_question() creates and returns one QuizQuestion, with exactly these values:

QuizQuestion(question="What does len([1, 2, 3]) return?", choices=["2", "3", "4"], answer_index=1)

QuizQuestion is already imported at the top of structured.py.

correct_choice(question) takes any QuizQuestion and returns the text of its correct choice: the item of question.choices at position question.answer_index. For the sample, that is "3".

A pydantic model only checks types, not whether the values make sense together. A QuizQuestion with two choices and answer_index=2 is perfectly valid to pydantic, and correct_choice then raises IndexError. Let it: an index past the last choice is a broken question, and the caller should hear about it rather than receive a made-up answer.

Run it

Run python structured.py. The demonstration builds your sample question, prints it, reads one field, calls correct_choice and dumps it:

A QuizQuestion from sample_question:
  QuizQuestion(question='What does len([1, 2, 3]) return?', choices=['2', '3', '4'], answer_index=1)
  question.question is 'What does len([1, 2, 3]) return?'
  correct_choice gives '3'
  model_dump() gives {'question': 'What does len([1, 2, 3]) return?', 'choices': ['2', '3', '4'], 'answer_index': 1}
Run stopped at the next function to build: QuizSet is written in Lesson 5, in quiz_models.py.

The first line shows how pydantic displays a model: its name and each field with its value. The run stops at QuizSet, the placeholder in quiz_models.py, which you write next.

question is a QuizQuestion. Which expression gives its list of choices?

A QuizQuestion has choices=["yes", "no"] and answer_index=5. What happens?

Task

In structured.py, replace the unfinished bodies of sample_question() and correct_choice(question).

  • sample_question() returns QuizQuestion(question="What does len([1, 2, 3]) return?", choices=["2", "3", "4"], answer_index=1).

  • correct_choice(question) returns the text of the correct choice: the item of question.choices at position question.answer_index.

correct_choice reads the fields with a dot and catches nothing: an answer_index past the last choice raises IndexError, and that error should reach the caller. Run python structured.py to see your question, then check your work.