Pydantic: Question about validating empty Lists

Created on 22 Jan 2019  路  3Comments  路  Source: samuelcolvin/pydantic

I have problem with validate lists. If I pass empty list to validator I don't have any ValidationError which should be thrown because List have declared values. If I pass to list any value, like empty str everything seems to work fine. Am I doing something wrong?

from typing import List
from pydantic import BaseModel,constr
class lists(BaseModel): 
    list1: List[constr(min_length=1, max_length=2)] = None
    list2: List[int]
    list3: List[str]

lists(**{'list1': [], 'list2': [], 'list3': []})
Out[2]: <lists list2=[] list3=[] list1=[]>

In [3]: lists(**{'list1': [''], 'list2': [''], 'list3': ['']})
ValidationError: 2 validation errors
list2 -> 0
  value is not a valid integer (type=type_error.integer)
list1 -> 0
  ensure this value has at least 1 characters (type=value_error.any_str.min_length; limit_value=1)

feature request question

Most helpful comment

This is "correct" since an empty list is a valid list and has no elements to validate.

What you need is conlist a bit list constr which constrains length, we discussed this in #161 but it hasn't been implemented.

PR welcome.

You could also do this with @validators.

All 3 comments

This is "correct" since an empty list is a valid list and has no elements to validate.

What you need is conlist a bit list constr which constrains length, we discussed this in #161 but it hasn't been implemented.

PR welcome.

You could also do this with @validators.

Small workaround for empty list

@validator('list1', 'list2', 'list3', pre=True, whole=True)
def check_if_list_has_value(cls, value):
    return value or None

Great.

Btw, just return value or None would be more succinct.

Was this page helpful?
0 / 5 - 0 ratings