Literal Type
noun
say it: “LIT-er-ul TYPE” /ˈlɪtərəl taɪp/
A Python type hint that lists the only values a variable or field may hold, such as Literal["dog", "cat", "rabbit"]; Pydantic refuses any other value.
What is a Literal type hint in Python?
A Literal type hint, from Python's typing module, lists the only values allowed, such as
Literal["dog", "cat", "rabbit"]. Python itself doesn't check it, but Pydantic and FastAPI do, and they match each
value exactly, so "Cat" isn't "cat".
from typing import Literal
from pydantic import BaseModel, ValidationError
class Application(BaseModel):
pet_type: Literal["dog", "cat", "rabbit"]
print(Application(pet_type="cat").pet_type) # cat
try:
Application(pet_type="Cat") # matched exactly, so "Cat" is refused
except ValidationError as error:
print(error.errors()[0]["type"]) # literal_error
In a sentence
- “With a Literal type of "open", "closed" and "muddy", a trail's status can't be anything else.”
- “The pet_type field uses a Literal type, so an application for a parrot gets a 422.”
Level: Journeyman · More Python terms at this level
Updated