Skip to content

feat: add support for objects with a model_dump method in depythonize - #119

Open
pscff wants to merge 1 commit into
davidhewitt:mainfrom
pscff:feat/model-dump-support
Open

pscff wants to merge 1 commit into
davidhewitt:mainfrom
pscff:feat/model-dump-support

Conversation

@pscff

@pscff pscff commented Sep 16, 2026

Copy link
Copy Markdown

Motivation

Pydantic-style models expose a model_dump() method that returns a dict. Currently depythonize cannot deserialize these objects because they are not Mapping instances. This PR adds support for calling model_dump() automatically.

Changes

  • Add model_dump_access() method to Depythonizer that:
    • Checks if the input object has a model_dump attribute
    • Calls it and expects a mapping (dict) result
    • Returns an error if the result is not a mapping
    • Returns None if the object has no model_dump method (falls through to other paths)
  • Call model_dump_access() from both deserialize_map and deserialize_any, so it works for struct deserialization (serde's primary dispatch path) as well as untyped deserialization (e.g. serde_json::Value)
  • Update depythonize doc comment to mention model_dump support

Test plan

  • test_model_dump: deserialize a custom Python class with model_dump() returning {'x':..., 'y':...} into a Rust struct, serde_json::Value, and HashMap<String, i32>
  • test_model_dump_non_mapping_error: verify that a model_dump() returning a non-mapping raises a clear error

All 89 existing + new tests pass.

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.

1 participant