Session 5· 09· 10 min

Enum & Nullable Fields

What you'll learn
  • Restrict a field to specific enum values
  • Mark optional fields as nullable
  • See how enums make downstream code safer

Two small but powerful schema features. enum restricts a field to a fixed set of values (great for categorical labels). nullable lets a field be explicitly null when the data is unknown.

09_schema_with_enum_and_nullable.py
schema = {
    "type": "object",
    "properties": {
        "sentiment": {
            "type": "string",
            "enum": ["positive", "neutral", "negative"],      ①
        },
        "confidence": {"type": "number"},
        "note": {"type": ["string", "null"]},                 ②
    },
    "required": ["sentiment", "confidence", "note"],
    "additionalProperties": False,
}
enum = exactly one of these three strings, nothing else.
To allow null, the type field becomes a LIST: ["string", "null"]. And the field must still be in required[].
$ python 09_schema_with_enum_and_nullable.py
Enum for classification
Any time you ask the model to pick a category (priority, tone, sentiment, status) — use an enum. It makes the downstream switch/if-else code safe because you know the exact set of possible values.
Code Check
How do you make a field that can be string OR null?
Recap — what you just learned
  • enum = restrict to a fixed set of values
  • Nullable = type is a list like ["string", "null"]
  • Nullable fields must still be in required[] — you choose absent vs null, not both
Next up: 10 — Format vs Tools