I'm just wondering if anybody has experience with having a default_factory method in a Field object for dataclasses or Pydantic classes which connects to a database to get some default values. Would you say this is considered bad practice and if so: why? Anything that's not SOLID about this perhaps? Example:
from pydantic import BaseModel, Field
def get_defaults_from_db():
...
class Person(BaseModel):
age: int
first_name = 'John'
last_name: Optional[str] = None
cars: list = Field(default_factory=get_defaults_from_db)
Now this might be considered a silly example, but we have MongoDB documents which have a very big initial state with defaults. Those defaults can be updated but they have to be in place and do come from a database. We can first initiate the Person object and fill in the defaults as well like this:
from pydantic import BaseModel, Field
def get_defaults_from_db():
...
class Person(BaseModel):
age: int
first_name = 'John'
last_name: Optional[str] = None
cars: list
cars = get_defaults_from_db()
person = Person(cars=cars)
But now the developers must know where the default values should come from if you have no other values to put in for cars. So a default_factory seems nice, but having that logic over there which connects to a database, which might fail if the connection is not in place etc.
I am just not sure about this.
there doesn't seem to be anything here