Skip to content

Commit

Permalink
Subclass validator each item docs (#1592)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
samueldeklund committed Jun 27, 2020
1 parent 7ac9faf commit 7bd635c
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions 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.
36 changes: 36 additions & 0 deletions 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)
10 changes: 10 additions & 0 deletions docs/usage/validators.md
Expand Up @@ -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.
Expand Down

0 comments on commit 7bd635c

Please sign in to comment.