bump-pydantic

repository·main·Indexed 43 days ago

https://github.com/pydantic/bump-pydantic

A CLI tool designed to automate the migration of Python codebases from Pydantic V1 to Pydantic V2 by applying predefined transformation rules. It handles updates for Config classes, Field parameters, imports, decorators, and constrained type functions, while providing options to preview changes via --diff or disable specific rules like BP001.

Tokens
1.9K
Snippets
13
Records
16
Agent score
53%

What's inside bump-pydantic

  1. Use bump-pydantic to migrate code

    main

    The bump-pydantic tool is a CLI used to automate Pydantic V1 to V2 migrations.

    To use it, navigate to your project root and point the command to the package directory containing your Python source files.

    Workflow:

    1. Check changes: Run with the --diff flag to see what will be changed without modifying files.
    2. Apply changes: Run the command on the target path to perform the migration.
    # Check diff before applying changes
    bump-pydantic --diff <path>
    
    # Apply changes
    bump-pydantic <path>
  2. Migration Rule BP010: Add type annotations or TODOs to fields

    main

    Ensures all fields have type annotations. It infers types for simple defaults (like bool, str, int, float) and adds # TODO[pydantic]: add type annotation for fields where the type cannot be inferred.

    # Before
    class Potato(BaseModel):
        is_sale = True
    
    # After
    class Potato(BaseModel):
        is_sale: bool = True
  3. Migration Rule BP005: Replace GenericModel with BaseModel

    main

    In Pydantic V2, GenericModel is no longer required; BaseModel supports generics directly.

    # Before
    from pydantic.generics import GenericModel
    class User(GenericModel, Generic[T]): ...
    
    # After
    from pydantic import BaseModel
    class User(BaseModel, Generic[T]): ...
  4. Migration Rule BP002: Replace Config class with model_config

    main

    Converts the inner class Config into a model_config = ConfigDict(...) attribute. It renames old attributes to their V2 equivalents, replaces the Extra enum with string values, and adds TODO comments where automatic transformation is not possible.

    # Before
    from pydantic import BaseModel, Extra
    
    class User(BaseModel):
        name: str
    
        class Config:
            extra = Extra.forbid
    
    # After
    from pydantic import ConfigDict, BaseModel
    
    class User(BaseModel):
        name: str
    
        model_config = ConfigDict(extra="forbid")
  5. Migration Rule BP006: Replace __root__ with RootModel

    main

    Converts models using the __root__ attribute to the new RootModel syntax.

    # Before
    class Users(BaseModel):
        __root__ = List[User]
    
    # After
    from pydantic import RootModel
    class Users(RootModel[List[User]]):
        pass
  6. Migration Rule BP007: Replace decorators

    main

    Updates validation decorators to their V2 counterparts:

    • @validator $\rightarrow$ @field_validator(..., mode='before') (or appropriate mode).
    • @root_validator $\rightarrow$ @model_validator(mode='before').
    # Before
    @validator('name', pre=True)
    def validate_name(cls, v): ...
    
    # After
    @field_validator('name', mode='before')
    def validate_name(cls, v): ...
  7. Migration Rule BP003: Replace Field parameters

    main

    Updates deprecated Field parameters to their V2 names (e.g., min_items to min_length). It also converts Enum constant fields to Literal types.

    # Before
    class User(BaseModel):
        name: List[str] = Field(..., min_items=1)
    
    # After
    class User(BaseModel):
        name: List[str] = Field(..., min_length=1)
  8. Migration Rule BP001: Add default None to Optional and Union fields

    main

    Automatically adds = None to fields typed with Optional[T], Union[T, None], or Any to ensure compatibility with V2 behavior.

    # Before
    class User(BaseModel):
        name: Optional[str]
    
    # After
    class User(BaseModel):
        name: Optional[str] = None
  9. Migration Rule BP009: Mark Pydantic protocol functions with TODOs

    main

    Identifies custom types using V1 protocol methods that require manual refactoring and adds TODO[pydantic] comments with migration guidance:

    • __get_validators__ $\rightarrow$ __get_pydantic_core_schema__.
    • __modify_schema__ $\rightarrow$ __get_pydantic_json_schema__.
  10. Migration Rule BP008: Replace con* functions with Annotated

    main

    Replaces constrained type functions (like constr, conint, confloat, etc.) with Annotated versions using StringConstraints or Field.

    # Before
    class User(BaseModel):
        name: constr(min_length=1)
    
    # After
    from typing_extensions import Annotated
    from pydantic import StringConstraints
    
    class User(BaseModel):
        name: Annotated[str, StringConstraints(min_length=1)]