From 7bd635c21c784e984afe4835334086c3d7c63dba Mon Sep 17 00:00:00 2001 From: Samuel Eklund Date: Sat, 27 Jun 2020 06:51:18 -0700 Subject: [PATCH] Subclass validator each item docs (#1592) * add description of subclass each_item scenario * add example of subclass validator with each_item * each_item causes validator to not run when parent class has List field #1566 --- changes/1566-samueldeklund.md | 1 + .../examples/validators_subclass_each_item.py | 36 +++++++++++++++++++ docs/usage/validators.md | 10 ++++++ 3 files changed, 47 insertions(+) create mode 100644 changes/1566-samueldeklund.md create mode 100644 docs/examples/validators_subclass_each_item.py diff --git a/changes/1566-samueldeklund.md b/changes/1566-samueldeklund.md new file mode 100644 index 0000000000..bd35c65d5e --- /dev/null +++ b/changes/1566-samueldeklund.md @@ -0,0 +1 @@ +Subclass validators do not run when referencing a `List` field defined in a parent class when `each_item=True`. Added an example to the docs illustrating this. diff --git a/docs/examples/validators_subclass_each_item.py b/docs/examples/validators_subclass_each_item.py new file mode 100644 index 0000000000..4b050950d9 --- /dev/null +++ b/docs/examples/validators_subclass_each_item.py @@ -0,0 +1,36 @@ +from typing import List +from pydantic import BaseModel, ValidationError, validator + + +class ParentModel(BaseModel): + names: List[str] + + +class ChildModel(ParentModel): + @validator('names', each_item=True) + def check_names_not_empty(cls, v): + assert v != '', 'Empty strings are not allowed.' + return v + + +# This will NOT raise a ValidationError because the validator was not called +try: + child = ChildModel(names=['Alice', 'Bob', 'Eve', '']) +except ValidationError as e: + print(e) +else: + print('No ValidationError caught.') + + +class ChildModel2(ParentModel): + @validator('names') + def check_names_not_empty(cls, v): + for name in v: + assert name != '', 'Empty strings are not allowed.' + return v + + +try: + child = ChildModel2(names=['Alice', 'Bob', 'Eve', '']) +except ValidationError as e: + print(e) diff --git a/docs/usage/validators.md b/docs/usage/validators.md index 26b588e4ec..c135124ecb 100644 --- a/docs/usage/validators.md +++ b/docs/usage/validators.md @@ -50,6 +50,16 @@ A few more things to note: * passing `each_item=True` will result in the validator being applied to individual values (e.g. of `List`, `Dict`, `Set`, etc.), rather than the whole object +## Subclass Validators and `each_item` + +If using a validator with a subclass that references a `List` type field on a parent class, using `each_item=True` will +cause the validator not to run; instead, the list must be iterated over programatically. + +```py +{!.tmp_examples/validators_subclass_each_item.py!} +``` +_(This script is complete, it should run "as is")_ + ## Validate Always For performance reasons, by default validators are not called for fields when a value is not supplied.