Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
Best practice to set default variable for pydantic field at runtime

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?

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!