Jump to solution
Verify

The Fix

pip install pydantic==2.10.6

Based on closed pydantic/pydantic issue #11133 · PR/commit linked

Production note: This usually shows up under retries/timeouts. Treat it as a side-effect risk until you can verify behavior with a canary + real traffic.

Jump to Verify Open PR/Commit
@@ -64,12 +64,11 @@ def __init__(self, metadata: Any): -def _update_fields_from_docstrings(cls: type[Any], fields: dict[str, FieldInfo], config_wrapper: ConfigWrapper) -> None: - if config_wrapper.use_attribute_docstrings: - fields_docs = extract_docstrings_from_cls(cls)
repro.py
# coding: utf-8 import json import typing as t from pydantic import ConfigDict, Field, BeforeValidator, BaseModel from pydantic.dataclasses import dataclass def _json_to_dict(data: str) -> dict: print("_json_to_dict", type(data), data) if not data: return {} # fixme: avoid exception if isinstance(data, dict): return data return json.loads(data) def _to_str(data: t.Any) -> str: print("_to_str", type(data), data) if isinstance(data, str): return data if not data: return "" return str(data) _CONFIG = ConfigDict( extra="allow", validate_assignment=True, arbitrary_types_allowed=True, coerce_numbers_to_str=True) @dataclass(config=_CONFIG) class B: a: t.Annotated[str, BeforeValidator(_to_str)] = "4" @dataclass(config=_CONFIG) class A: b: t.Annotated[B, BeforeValidator(_json_to_dict)] = Field(default_factory=B) class AA(BaseModel): b: t.Annotated[B, BeforeValidator(_json_to_dict)] = Field(default_factory=B) if __name__ == '__main__': data = {"b": json.dumps({"a": None, "b": 200})} a = A(**data) # _json_to_dict <class 'str'> {"a": null, "b": 200} # _json_to_dict <class 'dict'> {'a': None, 'b': 200} print(a) aa = AA(**data) # _json_to_dict <class 'str'> {"a": null, "b": 200} print(aa)
verify
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.
fix.md
Option A — Upgrade to fixed release\npip install pydantic==2.10.6\nWhen NOT to use: This fix should not be applied if the application relies on the original behavior of BeforeValidator.\n\n

Why This Fix Works in Production

  • Trigger: I added a conditional `if isinstance(data, dict): return data` to avoid exception. Or it report excpetion `TypeError: the JSON object must be str, bytes or…
  • Mechanism: Fixed an issue where the BeforeValidator `func` was called twice when the input field value was a JSON object in `pydantic.dataclass`.
  • Why the fix works: Fixed an issue where the BeforeValidator `func` was called twice when the input field value was a JSON object in `pydantic.dataclass`. (first fixed release: 2.10.6).
Production impact:
  • If left unfixed, retries/timeouts can trigger duplicate external side-effects (double charges, duplicate emails, repeated writes).

Why This Breaks in Prod

  • Shows up under Python 3.9 in real deployments (not just unit tests).
  • Production symptom (often without a traceback): I added a conditional `if isinstance(data, dict): return data` to avoid exception. Or it report excpetion `TypeError: the JSON object must be str, bytes or bytearray, not dict`.

Proof / Evidence

Discussion

High-signal excerpts from the issue thread (symptoms, repros, edge-cases).

“Sorry for the delay, bisected and this was fixed by https://github.com/pydantic/pydantic/pull/11246, which is available in 2.11.”
@Viicos · 2025-04-11 · source

Failure Signature (Search String)

  • I added a conditional `if isinstance(data, dict): return data` to avoid exception. Or it report excpetion `TypeError: the JSON object must be str, bytes or bytearray, not dict`.
Copy-friendly signature
signature.txt
Failure Signature ----------------- I added a conditional `if isinstance(data, dict): return data` to avoid exception. Or it report excpetion `TypeError: the JSON object must be str, bytes or bytearray, not dict`.

Error Message

Signature-only (no traceback captured)
error.txt
Error Message ------------- I added a conditional `if isinstance(data, dict): return data` to avoid exception. Or it report excpetion `TypeError: the JSON object must be str, bytes or bytearray, not dict`.

Minimal Reproduction

repro.py
# coding: utf-8 import json import typing as t from pydantic import ConfigDict, Field, BeforeValidator, BaseModel from pydantic.dataclasses import dataclass def _json_to_dict(data: str) -> dict: print("_json_to_dict", type(data), data) if not data: return {} # fixme: avoid exception if isinstance(data, dict): return data return json.loads(data) def _to_str(data: t.Any) -> str: print("_to_str", type(data), data) if isinstance(data, str): return data if not data: return "" return str(data) _CONFIG = ConfigDict( extra="allow", validate_assignment=True, arbitrary_types_allowed=True, coerce_numbers_to_str=True) @dataclass(config=_CONFIG) class B: a: t.Annotated[str, BeforeValidator(_to_str)] = "4" @dataclass(config=_CONFIG) class A: b: t.Annotated[B, BeforeValidator(_json_to_dict)] = Field(default_factory=B) class AA(BaseModel): b: t.Annotated[B, BeforeValidator(_json_to_dict)] = Field(default_factory=B) if __name__ == '__main__': data = {"b": json.dumps({"a": None, "b": 200})} a = A(**data) # _json_to_dict <class 'str'> {"a": null, "b": 200} # _json_to_dict <class 'dict'> {'a': None, 'b': 200} print(a) aa = AA(**data) # _json_to_dict <class 'str'> {"a": null, "b": 200} print(aa)

Environment

  • Python: 3.9
  • Pydantic: 2

What Broke

Users experienced TypeError exceptions when initializing dataclasses with JSON string inputs.

Fix Options (Details)

Option A — Upgrade to fixed release Safe default (recommended)

pip install pydantic==2.10.6

When NOT to use: This fix should not be applied if the application relies on the original behavior of BeforeValidator.

Use when you can deploy the upstream fix. It is usually lower-risk than long-lived workarounds.

Fix reference: https://github.com/pydantic/pydantic/pull/11246

First fixed release: 2.10.6

Last verified: 2026-02-09. Validate in your environment.

Get updates

We publish verified fixes weekly. No spam.

Subscribe

When NOT to Use This Fix

  • This fix should not be applied if the application relies on the original behavior of BeforeValidator.

Verify Fix

verify
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.

Did This Fix Work in Your Case?

Quick signal helps us prioritize which fixes to verify and improve.

Prevention

  • Add a CI check that diffs key outputs after upgrades (OpenAPI schema snapshots, JSON payload shapes, CLI output).
  • Upgrade behind a canary and run integration tests against the canary before 100% rollout.

Version Compatibility Table

VersionStatus
2.10.6 Fixed

Related Issues

No related fixes found.

Sources

We don’t republish the full GitHub discussion text. Use the links above for context.