How to give a Pydantic list field a default value?
Question:
I want to create a Pydantic model in which there is a list field, which left uninitialized has a default value of an empty list. Is there an idiomatic way to do this?
For Python’s built-in dataclass objects you can use field(default_factory=list)
, however in my own experiments this seems to prevent my Pydantic models from being pickled. A naive implementation might be, something like this:
from pydantic import BaseModel
class Foo(BaseModel):
defaulted_list_field: Sequence[str] = [] # Bad!
But we all know not to use a mutable value like the empty-list literal as a default.
So what’s the correct way to give a Pydantic list-field a default value?
Answers:
For pydantic you can use mutable default value, like:
class Foo(BaseModel):
defaulted_list_field: List[str] = []
f1, f2 = Foo(), Foo()
f1.defaulted_list_field.append("hey!")
print(f1) # defaulted_list_field=['hey!']
print(f2) # defaulted_list_field=[]
It will be handled correctly (deep copy) and each model instance will have its own empty list.
Pydantic also has default_factory
parameter. In the case of an empty list, the result will be identical, it is rather used when declaring a field with a default value, you may want it to be dynamic (i.e. different for each model).
from typing import List
from pydantic import BaseModel, Field
from uuid import UUID, uuid4
class Foo(BaseModel):
defaulted_list_field: List[str] = Field(default_factory=list)
uid: UUID = Field(default_factory=uuid4)
I want to create a Pydantic model in which there is a list field, which left uninitialized has a default value of an empty list. Is there an idiomatic way to do this?
For Python’s built-in dataclass objects you can use field(default_factory=list)
, however in my own experiments this seems to prevent my Pydantic models from being pickled. A naive implementation might be, something like this:
from pydantic import BaseModel
class Foo(BaseModel):
defaulted_list_field: Sequence[str] = [] # Bad!
But we all know not to use a mutable value like the empty-list literal as a default.
So what’s the correct way to give a Pydantic list-field a default value?
For pydantic you can use mutable default value, like:
class Foo(BaseModel):
defaulted_list_field: List[str] = []
f1, f2 = Foo(), Foo()
f1.defaulted_list_field.append("hey!")
print(f1) # defaulted_list_field=['hey!']
print(f2) # defaulted_list_field=[]
It will be handled correctly (deep copy) and each model instance will have its own empty list.
Pydantic also has default_factory
parameter. In the case of an empty list, the result will be identical, it is rather used when declaring a field with a default value, you may want it to be dynamic (i.e. different for each model).
from typing import List
from pydantic import BaseModel, Field
from uuid import UUID, uuid4
class Foo(BaseModel):
defaulted_list_field: List[str] = Field(default_factory=list)
uid: UUID = Field(default_factory=uuid4)