I have a pydantic model for request like below,
from pydantic import BaseModel, Field
from typing import List, ClassVar
from fastapi import FastAPI
app = FastAPI()
class myRequestModel(BaseModel):
items: List[str] = Field(..., example=['a','b'])
n: int = Field(100, example=50, gt=0)
@app.post("/test")
def test_func(args: myRequestModel):
dynamic_threshold = my_func(...) # let say dynamic_threshold is determined at runtime
if args.n < dynamic_threshold:
args.n = 100 # I want to assign args.n only when it is under dynamic_threshold
When users do not give n
, it is automatically set to 100 which is default value through Field
attribute.
If users give n
less than dynamic_threshold
, it needs to be set to default value.
In order to achieve this, I tried to add _default_n
using typing.ClassVar
. See below,
class myRequestModel(BaseModel):
_default_n: ClassVar[int] = 100
n: int = Field(_default_n, example=100, gt=0)
...
class Config:
underscore_attrs_are_private = True
@app.post("/test")
def test_func(args: myRequestModel):
...
if args.n < dynamic_threshold:
args.n = args._default_n <-- Here, I get a warning 'Access to a protected member _default_n of a class
This works, but I don't think this is not a right way for warning..
What is the appropriate way to make default value that can be used at runtime?