How to Enforce Length and Uniqueness
To enforce length constraints and uniqueness in collections, use the min_length, max_length, and specific schema types like SetSchema provided by pydantic-core.
Enforcing Length on Lists
To constrain the number of items in a list, use the min_length and max_length arguments in ListSchema.
from pydantic_core import SchemaValidator, core_schema as cs
# Define a list of integers that must have between 2 and 3 items
schema = cs.list_schema(cs.int_schema(), min_length=2, max_length=3)
v = SchemaValidator(schema)
# Valid input
assert v.validate_python([1, 2]) == [1, 2]
# Invalid input: too few items
# Raises ValidationError: List should have at least 2 items after validation, not 1
try:
v.validate_python([1])
except Exception as e:
print(e)
Enforcing Uniqueness and Length on Sets
In pydantic-core, uniqueness is enforced by using SetSchema or FrozenSetSchema. These schemas automatically deduplicate input items into a Python set or frozenset. Length constraints are applied after this deduplication.
from pydantic_core import SchemaValidator, core_schema as cs
# Define a set that must have at most 3 unique items
schema = cs.set_schema(cs.int_schema(), max_length=3)
v = SchemaValidator(schema)
# Input with duplicates is deduplicated before the length check
# [1, 1, 2, 2, 3, 3] becomes {1, 2, 3}, which has length 3 (Valid)
assert v.validate_python([1, 1, 2, 2, 3, 3]) == {1, 2, 3}
# Invalid input: too many unique items
# [1, 2, 3, 4] has length 4 (Invalid)
# Raises ValidationError: Set should have at most 3 items after validation, not 4
try:
v.validate_python([1, 2, 3, 4])
except Exception as e:
print(e)
For immutable sets, use FrozenSetSchema:
schema = cs.frozenset_schema(cs.int_schema(), min_length=1)
v = SchemaValidator(schema)
assert v.validate_python([1, 2]) == frozenset({1, 2})
Enforcing Length on Dictionaries
DictSchema supports min_length and max_length to control the number of key-value pairs allowed in the dictionary.
from pydantic_core import SchemaValidator, core_schema as cs
# Define a dictionary that must have at least 3 items
schema = cs.dict_schema(min_length=3)
v = SchemaValidator(schema)
# Valid input
assert v.validate_python({'a': 1, 'b': 2, 'c': 3}) == {'a': 1, 'b': 2, 'c': 3}
# Invalid input: too few items
# Raises ValidationError: Dictionary should have at least 3 items after validation, not 2
try:
v.validate_python({'a': 1, 'b': 2})
except Exception as e:
print(e)
Stopping Early with Fail Fast
By default, pydantic-core attempts to validate all items in a collection and collect all errors. To stop validation immediately after the first error is encountered (including length violations or item validation failures), set fail_fast=True.
from pydantic_core import SchemaValidator, core_schema as cs
schema = cs.list_schema(cs.int_schema(), min_length=5, fail_fast=True)
v = SchemaValidator(schema)
# Validation stops at the first failure rather than checking every element
Troubleshooting and Constraints
Uniqueness in Lists
The unique_items constraint for lists is not supported in pydantic-core. If you need to ensure all items in a collection are unique, you should use SetSchema or FrozenSetSchema. If you must return a list but require uniqueness during validation, you can use a set_schema and then a function-after validator to convert the result back to a list.
Length Check Timing
Length constraints are applied to the collection after the individual items have been validated. For sets, this means the length is checked after duplicates have been removed. For lists and dictionaries, if an item fails validation and is excluded (depending on the specific validator configuration), it will not count toward the final length.
Dictionary Key Errors
When a dictionary fails validation due to a key error, the error location will include a [key] suffix. For example, an error in a key named my_key would be reported at the path ('my_key', '[key]').