Skip to content

Reject non-mapping input when deserializing a dataclass from dict - #815

Merged
yukinarit merged 1 commit into
yukinarit:mainfrom
cristianchiriac:fix-from-dict-non-mapping
Oct 22, 2026
Merged

yukinarit merged 1 commit into
yukinarit:mainfrom
cristianchiriac:fix-from-dict-non-mapping

Conversation

@cristianchiriac

Copy link
Copy Markdown
Contributor

Fixes #811

from_dict() on a dataclass checked fields with "name" in data. That also works on lists and strings, so from_dict(Policy, []) or from_dict(Policy, "") returned Policy() built from the defaults instead of failing.

The generated dict deserializer now raises SerdeError when data is not a Mapping. A plain dict is matched first with an exact class check, so the common case skips the isinstance(..., Mapping) call. {} still gives the defaults, and other mappings such as OrderedDict and MappingProxyType still work. The same check covers nested dataclass fields. In untagged unions, a list or string no longer matches a dataclass member just because that member has defaults.

The check uses the global name _Mapping because the generated code already stores field type names in that namespace.

Tests: added test_from_dict_rejects_non_mapping in tests/test_basics.py. It fails on main and passes with this change. Full suite (pytest tests --doctest-modules serde -nauto): 5298 passed, 2 skipped, 1 xfailed. Examples pass, and the pre-commit hooks (black, ruff, mypy, pyright) pass on the changed files.

This is related to #809, which deals with sequence fields; both PRs add Mapping to the same import line in serde/de.py.

from_dict() looked up fields with `"name" in data`, which also works on
lists and strings, so inputs like [] or "" silently produced a dataclass
built from its defaults. The generated dict deserializer now raises
SerdeError unless data is a Mapping. {} still uses the defaults.

Fixes #811
@yukinarit yukinarit added the enhancement New feature or request label Oct 22, 2026

@yukinarit yukinarit left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, thank you!

@yukinarit
yukinarit merged commit 13926a6 into yukinarit:main Oct 22, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

from_dict() accepts non-mapping inputs for dataclass targets

2 participants