Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix enum serialization problems #458

Merged
merged 1 commit into from
Nov 12, 2024
Merged

Conversation

jduerholt
Copy link
Contributor

As outlined here https://stackoverflow.com/questions/69541613/how-to-json-serialize-enum-classes-in-pydantic-basemodel, the json module has problems with serializing plain enums, so far we had to use always pydantics model_dump_json. This can lead to problems and confusion.

Setting up enums which also inherit from str solves this issue. In py3.11 is a new datatype available which does exactly this called StrEnum (https://docs.python.org/3/library/enum.html#enum.StrEnum). But due to backwards compatibility, I implemented the solution to explicitly inherit from str.

@bertiqwerty
Copy link
Contributor

bertiqwerty commented Nov 12, 2024

Thanks Johannes. What do you mean with

so far we had to use always pydantics model_dump_json. This can lead to problems and confusion.

?

@jduerholt
Copy link
Contributor Author

The problem is that if you do not change it in this way, pydantic serializes it to "EnumA.ValueA", if you pass default=str to json.dumps, it is able to serialize the enum but it gives you just ValueA. With the changes, you do not have to pass default=str, and both serialize in the same way. I had problems with both working with requests and using TinyDB to store bofire based documents and get it back from the storage. This PR solves it.

@bertiqwerty
Copy link
Contributor

Does it work with old BoFire objects that already have been stored somewhere?

@jduerholt
Copy link
Contributor Author

Could lead to some Problems. But I think it is still good to merge it in, as this creates in general less problems. One can write a two liner to fix the old jsons.

@jduerholt jduerholt merged commit 811fcbf into main Nov 12, 2024
8 of 9 checks passed
@jduerholt jduerholt deleted the hotfix/enum_serialization branch November 12, 2024 21:26
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.

2 participants