Home > Software design >  Initialize FastAPI BaseModel using non keywords arguments (a.k.a *args)
Initialize FastAPI BaseModel using non keywords arguments (a.k.a *args)

Time:05-18

I have a FastApi item that I am trying to initialize using python tuples,

from pydantic import BaseModel

class Item(BaseModel):
     name: str = ""
     surname: str = ""

data = ("jhon", "dhon")
Item(*data)

Output the following error

TypeError: __init__() takes 1 positional argument but 3 were given

Is there a way to initialize a BaseModel from a tuple ?

CodePudding user response:

No, Pydantic models can only be initialized with keyword arguments. If you absolutely must initialize it from positional args, you can look at the schema:

>>> Item(**dict(zip(Item.schema()["properties"], data)))
Item(name='jhon', surname='dhon')

CodePudding user response:

I wrote a helper function that can load data from the tuple,

def fill_model_from_args(model: BaseModel, data: Tuple):
    base_model = model()
    keys = base_model.dict().keys()
    if len(keys) != len(data):
        raise ValueError("Can't load data to model...")
    return model(**{k: v for k, v in zip(keys,data)})
  • Related