Allow positional arguments for BaseModel pydantic

Viewed 160

I have a class with all the necessary parameters. But, for init function, it asks for keyword arguments, and does not accept positional arguments. So, my question is: is there something I can change in config of pydantic.BaseModel to allow positional arguments?

Here is an example of my class:

class Foo(BaseModel):
    a: int
    b: Optional[str]
    c: Optional[float]

And when I init the class, I need to pass keyword arguments: Image of a class parameters

So, I cannot initialize the class like this:

Foo(1,2,2.5)
# instead, I should init it like this:
Foo(a=1,b=2,c=2.5)

So, I need to be able to pass positional keywords to the class. Is it possible?

1 Answers

Pydantic objects can't be init with positional arguments.

import json
from pydantic import BaseModel
from typing import Optional

class Foo(BaseModel):
    a: int
    b: Optional[str]
    c: Optional[float]

You have to give Pydantic every key you want to init your model with (what you did):

Foo(a=1,b=2,c=2.5)

Or you can use a json:

json_raw = '{"a": 1, "b": 2, "c": 3}'
some_dict = json.loads(json_raw)
my_foo = Foo(**some_dict)

Why is that ? Here are some reasons:

  • when you have lot of fields - it would be very easy to add another field into a model and suddenly all code which assumes fields have a given position breaks silently
  • annotation only fields mean the order of pydantic model fields different from that in code, see here.
Related