AskReference
ConceptIntroductory

In the FastAPI example from Chapter 5, what does the type hint `list[Creature]` in the `get_creatures` function and the `get_all` endpoint indicate?

The type hint `list[Creature]` indicates that the value returned is a list containing only `Creature` objects, not other types. It appears both in the `get_creatures` data function and the `get_all` web endpoint, so both are expected to return lists of `Creature` instances.

In Example 5-10, `_creatures: list[Creature]` and `get_creatures() -> list[Creature]` tell Python that the data source holds and returns a list whose elements are all `Creature` objects. In Example 5-11, `get_all() -> list[Creature]` applies the same constraint to the FastAPI endpoint, meaning the endpoint returns a list of `Creature` models. The book explicitly states that `list[Creature]` tells Python that this is a list of `Creature` objects only. This type hint also lets FastAPI and Pydantic validate and serialize the return value appropriately, converting the `Creature` objects into a JSON array.

Key points

  • `list[Creature]` means a list that contains only `Creature` instances.
  • In `data.py`, `get_creatures` is typed to return such a list from the fake data source.
  • In `web.py`, `get_all` is typed to return the same list type from the FastAPI endpoint.
  • The book notes this hint tells Python the list consists of `Creature` objects only.
Source:FastAPI: Modern Python Web Development· Pydantic, Type Hints, and Models Tour· p. 85–93

Related questions

Cover of FastAPI: Modern Python Web Development

FastAPI: Modern Python Web Development

Bill Lubanovic;

First Edition · O'Reilly Media, Inc.

View this ebook