Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow positional arguments for BaseModel pydantic

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

Example of override __init__ method with type hint which works in pycharm

class Foo(BaseModel):
    a: int
    b: Optional[str]
    c: Optional[float]
    
    def __init__(self, a: int,
                 b: Optional[str] = None,
                 c: Optional[float] = None,
                 **kwargs) -> None:
        super(Foo, self).__init__(a=a, b=b, c=c, **kwargs)
like image 122
Arseniy Lebedev Avatar answered Dec 20 '25 08:12

Arseniy Lebedev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!