litestar-org / litestar-org/polyfactory

Guard by_name kwarg for pydantic < 2.11

Open Beginner friendly
#882 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.5k
Forks
120
PR merge metrics
No merged PRs in 30d

Description

### 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:

```python
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`.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at polyfactory/factories/pydantic_factory.py:570 and reproduce the failure with pydantic 2.10.6 when __by_name__ is enabled. Check the version compatibility around model_validate, then verify that pydantic below 2.11 omits by_name while 2.11 and newer retain the existing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
84/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.