pydantic / bump-pydantic

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

Add support for handling unannotated fields #149

Closed tiangolo closed 4 months ago

tiangolo commented 5 months ago

In Pydantic v1 it was okay to have fields without an explicit annotation:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    enabled = True
    description = "An item"

In Pydantic v2, it's required to have annotations in all fields, including fields with default values.

Problem

The current only way to detect the fields that need an annotation is to run the code, wait for the runtime error, and go and update the field. Then do it again to detect the next error.

But when startup is slow because the app is huge and has import side effects (e.g. connecting to a DB, importing ML models), the iteration speed can be very slow.

Desired Result

I would like bump-pydantic to add an annotation automatically, changing from:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    enabled = True
    description = "An item"

...to:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    enabled: bool = True
    description: str = "An item"

Desired Result 2

I imagine the result above might be difficult to achieve as some default values would probably require runtime.

So alternatively, I would like bump-pydantic to add a # TODO (pydantic v2): comment on top of each field that doesn't have an annotation, from:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    enabled = True
    description = "An item"

...to:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    # TODO (pydantic v2): Add a type annotation to this field
    enabled = True
    # TODO (pydantic v2): Add a type annotation to this field
    description = "An item"

This way I could run bump-pydantic once, and then see all the changes in git in the places where I need to add annotations, instead of having to start the whole application once per each field that needs it.