[Fixed] Pydantic V2 – field_validator() got an unexpected keyword argument 'pre' – Pydantic

by
Ali Hasan
llama-cpp-python pydantic

Quick Fix: Replace the pre=True argument with mode='before'. For example, in Pydantic v1:

@validator("x", pre=True)

In Pydantic v2, becomes:

@field_validator("x", mode="before")

The Problem:

During migration from Pydantic v1 to v2, the user is facing an issue while replacing @validator with @field_validator. Upon using the previously employed pre validator argument in @field_validator, an error is encountered: TypeError: field_validator() got an unexpected keyword argument 'pre'. Despite the documentation mentioning pre under the @field_validator section, it is unclear whether pre has been deprecated in v2.

The Solutions:

Solution 1: Use the `mode=”before”` argument

To replace the deprecated pre=True argument from Pydantic v1 in v2, use the mode="before" argument in @field_validator.

Example:

# Pydantic v1
class Foo(BaseModel):
    x: int

    @validator("x", pre=True)
    def do_stuff(cls, v: object) -> object:
        if v is None:
            return 0
        return v

# Pydantic v2
class Foo(BaseModel):
    x: int

    @field_validator("x", mode="before")
    def do_stuff(cls, v: object) -> object:
        if v is None:
            return 0
        return v

Q&A

What can I use instead of pre when migrating from Pydantic v1 to v2?

pre has been removed. Use mode="before" with field_validator instead.

Where in the documentation can I find information about using mode="before" with field_validator?

See the field_validator API reference.