OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Instantiate pydantic model without optional fields

  • Thread starter Thread starter AJP
  • Start date Start date
A

AJP

Guest
The following code shows a pylance (pyright) error for AModel() of Argument missing for parameter "field_b":

Code:
from pydantic import BaseModel, Field
from typing import Optional, Any

class AModel(BaseModel):
   field_a: str = Field()
   field_b: Optional[bool] = Field(None)

instance_1 = AModel(field_a="", field_b=None)  # No error
instance_2 = AModel(field_a="")  # Error
#            ^^^^^^^^^^^^^^^^^^

kwargs: dict[str, Any] = {"field_a": "", "field_bad": True}
instance_3 = AModel(**kwargs)  # No error but no type checking

Is it possible to instantiate this model without providing field_b=None and whilst retaining type checking?
<p>The following code shows a pylance (pyright) error for <code>AModel()</code> of <code>Argument missing for parameter "field_b"</code>:</p>
<pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel, Field
from typing import Optional, Any

class AModel(BaseModel):
field_a: str = Field()
field_b: Optional[bool] = Field(None)

instance_1 = AModel(field_a="", field_b=None) # No error
instance_2 = AModel(field_a="") # Error
# ^^^^^^^^^^^^^^^^^^

kwargs: dict[str, Any] = {"field_a": "", "field_bad": True}
instance_3 = AModel(**kwargs) # No error but no type checking
</code></pre>
<p>Is it possible to instantiate this model without providing <code>field_b=None</code> and whilst retaining type checking?</p>
 

Latest posts

Online statistics

Members online
0
Guests online
3
Total visitors
3
Top