ValidatedDict¶
- class bpod_core.misc.ValidatedDict ¶
Bases:
RootModel,MutableMappingA dict-like container with runtime validation for keys and values.
This class wraps a standard
dictand integrates with Pydantic’sRootModelto validate keys and values upon mutation. It behaves like a mutable mapping for all common operations (get, set, delete, iterate, len) and compares equal to regular dicts with the same contents.Examples
Subclass
ValidatedDictto create a custom type with validation:>>> class TestDict(ValidatedDict[str, int]): ... pass
You can then instantiate your class
TestDictlike a regular dict:>>> test_dict = TestDict() >>> test_dict['foo'] = 1 >>> test_dict[42] = 2 Traceback (most recent call last): ... pydantic_core._pydantic_core.ValidationError: 1 validation error for TestDict 42.[key] Input should be a valid string [type=string_type, input_value=42, input_type=int] ...
Alternatively, you can also instantiate a ValidatedDict directly:
>>> my_validated_dict = ValidatedDict[str, int]({'foo': 1, 'bar': 2}) >>> my_validated_dict['foo'] = 'bar' Traceback (most recent call last): ... pydantic_core._pydantic_core.ValidationError: 1 validation error ... foo Input should be a valid integer, unable to parse string as an integer ... ...