Skip to content

Guard by_name kwarg for pydantic < 2.11 #882

Description

@xyf5432

Summary

polyfactory/factories/pydantic_factory.py:570 calls
cls.__model__.model_validate(kwargs, by_name=True) when __by_name__ is set.

The by_name keyword argument was added to model_validate in pydantic 2.11.0.
On pydantic < 2.11 it raises

TypeError: BaseModel.model_validate() got an unexpected keyword argument 'by_name'

(verified on pydantic 2.10.6).

The project declares pydantic[email]>=2.10.4, which permits versions below
2.11, so the option can only be used on pydantic >= 2.11 in practice.

Impact

  • TypeError at factory build time on pydantic 2.10.4–2.10.x when a factory
    sets __by_name__ = True.
  • The declared minimum (2.10.4) does not actually support the feature.

Suggested fix

Guard the by_name argument with a pydantic version check, keeping the
existing behavior on pydantic >= 2.11:

if cls.__by_name__ and _is_pydantic_v2_model(cls.__model__):
    if _PYDANTIC_HAS_BY_NAME:  # pydantic >= 2.11
        return cls.__model__.model_validate(kwargs, by_name=True)
    return cls.__model__.model_validate(kwargs)

Alternatively, raise the minimum declared version to pydantic>=2.11.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions