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

dicts are serialized wrongly when assigned to an attribute with an 'Any' type #192

Open
Gollimnar opened this issue May 7, 2024 · 0 comments

Comments

@Gollimnar
Copy link

Class members typed as 'Any' will have their value serialized using default_object_serializer(). This produces wrong results for dict objects. For example:

from typing import Any, Dict
import jsons

# BadClass will fail to serialize properly.
class BadClass:
    key: str
    value: Any # This is the problem.

bc = BadClass()
bc.key = "bad"
bc.value = {"a": "b", "c": "d", "e": "f"}

print(jsons.dumps(bc))


# GoodClass will work as expected.
class GoodClass:
    key: str
    value: Dict[str, Any]

gc = GoodClass()
gc.key = "good"
gc.value = {"a": "b", "c": "d", "e": "f"}

print(jsons.dumps(gc))

The expected result:

{"key": "bad", "value": {"a": "b", "c": "d", "e": "f"}}
{"key": "good", "value": {"a": "b", "c": "d", "e": "f"}}

The actual result:

{"key": "bad", "value": {"clear": {}, "copy": {}, "fromkeys": {}, "get": {}, "items": {}, "keys": {}, "pop": {}, "popitem": {}, "setdefault": {}, "update": {}, "values": {}}}
{"key": "good", "value": {"a": "b", "c": "d", "e": "f"}}

Perhaps Any-types (as well as union types?) should be special cases and infer the serializer from the actual value?

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

No branches or pull requests

1 participant