Make BaseModel.to_dict() return JSON-serializable values (#93)#227
Open
CedricConday wants to merge 1 commit into
Open
Make BaseModel.to_dict() return JSON-serializable values (#93)#227CedricConday wants to merge 1 commit into
CedricConday wants to merge 1 commit into
Conversation
to_dict() returned enum-typed attributes as raw Enum objects (and UUID-typed attributes as raw UUID objects), so json.dumps(model.to_dict()) raised 'Object of type ... is not JSON serializable'. Register Enum and UUID handlers on serialize_to_dict so enums serialize to their .value and UUIDs to their canonical hyphenated string. Closes XeroAPI#93.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #93
BaseModel.to_dict()is documented as returning the model properties as a dict, but enum-typed attributes come back as the rawEnumobject, so:serialize_to_dict(thesingledispatchused byto_dict) has handlers forBaseModel,list,tupleanddict, but none forEnum, so enums fall through the identity default. The same applies toUUIDfields (see #161).Change
Register
EnumandUUIDhandlers onserialize_to_dict(theEnumhandler is exactly what was suggested in the issue):Test
Added
tests/test_models.pycovering enum→value, UUID→string, and thatjson.dumps(model.to_dict())no longer raises. The tests fail onmasterand pass with the fix; existing suite stays green.AI-assisted, human-reviewed — I'm an AI engineer; I find, fix, and test with AI, then review and verify before opening.