Literals, Enums, and UUIDs
In pydantic-core, restricting values to specific constants, Python Enum members, or UUIDs is handled by specialized schema types. These schemas ensure that input data matches a predefined set of allowed values or follows a specific format, providing both validation and, in the case of Enums, conversion to Python objects.
Literals
The LiteralSchema (created via literal_schema) is used to restrict a field to a specific set of values. This is the most basic form of constant restriction and is frequently used for exact matching of strings, integers, or other primitive types.
Core Implementation
A LiteralSchema requires an expected list of values. During validation, the input must match one of these values exactly.
from pydantic_core import SchemaValidator, core_schema
# Defined in pydantic-core/python/pydantic_core/core_schema.py
schema = core_schema.literal_schema(['hello', 'world'])
v = SchemaValidator(schema)
assert v.validate_python('hello') == 'hello'
Use in Discriminators
Literals are a fundamental building block for TaggedUnionSchema. By using a LiteralSchema for a specific field (often called a "type" or "kind" field), pydantic-core can efficiently determine which branch of a union to validate against.
Enums
The EnumSchema (created via enum_schema) provides a way to validate input against Python enum.Enum classes. Unlike literals, which return the raw value, EnumSchema typically returns an instance of the Enum class.
Core Implementation
The schema requires the Enum class (cls) and a list of its members.
from enum import Enum
from pydantic_core import SchemaValidator, core_schema
class Color(Enum):
RED = 1
GREEN = 2
# Defined in pydantic-core/python/pydantic_core/core_schema.py
schema = core_schema.enum_schema(
Color,
list(Color.__members__.values())
)
v = SchemaValidator(schema)
# Validates raw value and returns Enum member
assert v.validate_python(1) is Color.RED
Specialized Enums and Custom Lookups
EnumSchema supports several advanced configurations:
sub_type: Can be set to'str','int', or'float'. This is used when the Enum inherits from a primitive type (e.g.,class MyEnum(str, Enum)), allowing the validator to apply type-specific logic.missing: A callable that acts like Python's_missing_method. If a value is not found in thememberslist, this function is called to attempt a custom lookup.
UUIDs
The UuidSchema (created via uuid_schema) validates that a value is a valid Universally Unique Identifier. It supports both raw uuid.UUID objects and string/byte representations.
Version Validation
You can restrict validation to specific UUID versions using the version parameter. The uuid_schema function supports versions 1, 3, 4, 5, 6, 7, and 8.
from pydantic_core import SchemaValidator, core_schema
# Restrict to UUID v4
schema = core_schema.uuid_schema(version=4)
v = SchemaValidator(schema)
# Validates a v4 UUID string
v.validate_python('f47ac10b-58cc-4372-a567-0e02b2c3d479')
Strictness and Validation Modes
Strictness is a key concept across these three schema types, determining how much coercion is allowed during validation.
| Schema Type | Lax Mode (Default) | Strict Mode (strict=True) |
|---|---|---|
| Literal | Matches values exactly. | Matches values exactly (no difference in behavior for primitives). |
| Enum | Accepts raw values (like 1) and converts them to Enum members. | Only accepts actual instances of the Enum class (e.g., Color.RED). |
| UUID | Accepts UUID objects, valid UUID strings, or bytes. | Only accepts actual uuid.UUID instances. |
Strictness Example in Enums
In pydantic-core, setting strict=True on an EnumSchema prevents the validator from looking up members by their underlying values:
# Strict Enum validation
strict_schema = core_schema.enum_schema(
Color,
list(Color),
strict=True
)
v = SchemaValidator(strict_schema)
# This will raise a ValidationError because it's an int, not a Color instance
# v.validate_python(1)
# This is required in strict mode
assert v.validate_python(Color.RED) is Color.RED
UUID Format Validation
In lax mode, UuidSchema performs robust string validation. It ensures the string follows the standard UUID format before attempting to create a uuid.UUID object, ensuring consistent error reporting across different input types.