I am proposing an elegant solution.
from pydantic import BaseModel
from typing import List
from enum import Enum
class Fruit(str, Enum):
APPLE = 'apple'
BANANA = 'banana'
MELON = 'melon'
class UserForm(BaseModel):
fruits: List[Fruit]
name: str
And that's it.
- you don't need to write your own validator
- just tell pydantic you need a list of Fruit object, and it will do it for you
Check the above code:
put the above code in a file main.py
.
Run
python -i main.py
>>> uf = UserForm(fruits=['apple','banana'],name='hello')
>>> uf
UserForm(fruits=[<Fruit.APPLE: 'apple'>, <Fruit.BANANA: 'banana'>], name='hello')
>>> af = UserForm(fruits=['monkey','apple'],name='hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pydantic/main.py", line 400, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for UserForm
fruits -> 0
value is not a valid enumeration member; permitted: 'apple', 'banana', 'melon' (type=type_error.enum; enum_values=[<Fruit.APPLE: 'apple'>, <Fruit.BANANA: 'banana'>, <Fruit.MELON: 'melon'>])
>>>
pydantic will raise an error, as monkey
is not in fruits.