I have a use case where I want to create some values inside my class on the construction of the model. However, when I return the class to FastAPI for converting to JSON when I call the API, the constructor gets run again and I can get differing values from my original instance.
Here is a contrived example to illustrate:
class SomeModel(BaseModel):
public_value: str
secret_value: Optional[str]
def __init__(self, **data):
super().__init__(**data)
# this could also be done with default_factory
self.secret_value = randint(1, 5)
def some_function() -> SomeModel:
something = SomeModel(public_value="hello")
print(something)
return something
@app.get("/test", response_model=SomeModel)
async def exec_test():
something = some_function()
print(something)
return something
The console output is:
public_value='hello' secret_value=1
public_value='hello' secret_value=1
But the JSON in the web API is:
{
"public_value": "hello",
"secret_value": 2
}
When I step through the code I can see the __init__
being called twice.
First on the construction something = SomeModel(public_value="hello")
.
Second, which is unexpected to me, is in the API handler exec_test
on the return something
call.
If this is the wrong method to set up some internal data within the class please let me know the correct method to use. Otherwise, this seems like this is unintended behavior of one of the modules.