Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda