Skip to content

fix: respect default_factory for abstract generic fields in from_dict#570

Open
sanjibani wants to merge 1 commit into
lidatong:masterfrom
sanjibani:fix/mutable-mapping-default-factory
Open

fix: respect default_factory for abstract generic fields in from_dict#570
sanjibani wants to merge 1 commit into
lidatong:masterfrom
sanjibani:fix/mutable-mapping-default-factory

Conversation

@sanjibani

Copy link
Copy Markdown

Problem

When a dataclass field is typed as an abstract generic collection (e.g. MutableMapping[str, str]) and given a default_factory, calling from_dict({}) raises TypeError: MutableMapping() takes no arguments.

Fixes #505.

Root cause

In _decode_dataclass, fields missing from the input dict are correctly populated via default_factory(). However, the subsequent decoding loop still calls _decode_generic on that already-correct value, which attempts to instantiate the abstract MutableMapping type directly.

Fix

Track which fields were populated by default_factory (as opposed to arriving from the input data). In the decode loop, skip _decode_generic for those fields and pass the factory-produced value through as-is.

Test

Added a regression test in tests/test_collections.py covering both the empty-dict case and a full round-trip:

```python
@DataClass
class MyClass(DataClassJsonMixin):
field1: MutableMapping[str, str] = field(default_factory=dict)

MyClass.from_dict({}) # previously raised TypeError
MyClass.from_dict(MyClass(field1={"key": "value"}).to_dict()) # round-trip
```

Full test suite: 323 passed, 4 skipped, 0 failures.

🤖 Generated with Claude Code

When a field typed as an abstract generic (e.g. MutableMapping[str, str])
has a default_factory, calling from_dict({}) previously raised
TypeError: MutableMapping() takes no arguments. Track fields populated
by default_factory and skip _decode_generic for them.

Fixes lidatong#505

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
sanjibani added a commit to sanjibani/sanjibani that referenced this pull request Jun 16, 2026
… OSS repos

- merged: withastro/astro#17088 (docs: remove dead llms.txt)
- open: vercel/next.js#94846 (eslint-plugin-next fix), #94850 (docs links)
- open: denoland/deno#35266, vitejs/vite#22694, BerriAI/litellm#30530
- open: pixijs/pixijs#12094, mattermost/mattermost-mobile#9649 #9650
- open: lidatong/dataclasses-json#570, The-OpenROAD-Project/ORAssistant#258 #260

Star badges via shields.io. Sorted by repo stars descending.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Generic Collections fields - not respecting default_factory field specifications

1 participant