pydantic / bump-pydantic

Convert Pydantic from V1 to V2 ♻
MIT License
317 stars 24 forks source link

Required Optional field that uses `Field(...)` is made Non-Required #113

Closed ltuijnder closed 1 year ago

ltuijnder commented 1 year ago

Required Optional Fields (eg. fields that are allowed to be None but should explicitly be specified) are made non-Required when Field + ... ellipse was used.

For example, using bump-pydantic on the official pydantic v1.10 example: https://docs.pydantic.dev/1.10/usage/models/#required-optional-fields

Turns the following code:

from typing import Optional
from pydantic import BaseModel, Field, ValidationError

class Model(BaseModel):
    a: Optional[int]
    b: Optional[int] = ...
    c: Optional[int] = Field(...)

Into:

from typing import Optional
from pydantic import BaseModel, Field, ValidationError

class Model(BaseModel):
    a: Optional[int] = None
    b: Optional[int] = ...
    c: Optional[int] = Field(None)

While one would have expected:

from typing import Optional
from pydantic import BaseModel, Field, ValidationError

class Model(BaseModel):
    a: Optional[int] = None
    b: Optional[int] = ...
    c: Optional[int] = Field(...)

bump-pydantic version = v0.6.1 (as of writing the lastest version)

Kludex commented 1 year ago

Right. Wanna try to create a PR for it? 👀

brian-goo commented 1 year ago

It looks like None IS NOT added if nothing was specified for default in the first place as below. Is this expected behavior?

class Spam(BaseModel):
    s: int | None = Field(description="spam")
brian-goo commented 1 year ago

@Kludex I tried to fix this issue with https://github.com/pydantic/bump-pydantic/pull/126