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

Serialization of Enum type should use values rather than keys #18

Closed
cypreess opened this issue Mar 4, 2019 · 2 comments
Closed

Serialization of Enum type should use values rather than keys #18

cypreess opened this issue Mar 4, 2019 · 2 comments

Comments

@cypreess
Copy link

cypreess commented Mar 4, 2019

Given the following example Enum type:

from enum import Enum

class TestEnum(Enum):
    KEY = 'value`

jsons.dumps(TestEnum.KEY) will result in "KEY" (Deserialization works correctly).

However, this is behavior is a little bit irrational in regards to what enum is (used to be in C :) ). Enums classically are used to map some "codenames" for binary values (like numbers 0, 1, 2, 3). Therefore the value of enum should be binary representation generally used in serialization and keys should be something assigned for it on the high level (on runtime/ in the codebase).


Update: just for a reference standard lib json module does not serialize Enum's at all.

@ramonhagenaars
Copy link
Owner

Hi cypreess, thanks for the issue.

The choice for serializing the key rather than the value of an enum was made because of the readability of the serialized output.

Consider having the following construction:

class Pet(Enum):
    CAT = 1
    DOG = 2

@dataclass
class Person:
    name: str
    pet: Pet

And:

p = Person('John', Pet.CAT)
jsons.dump(p)

This results in:

{'name': 'John', 'pet': 'CAT'}

Rather than:

{'name': 'John', 'pet': 1}

The former is more self-explaining.

You can still serialize enums by their key if you wanted to:

jsons.dump(Pet.CAT, use_enum_name=False)
jsons.load(1, use_enum_name=False)

@cypreess
Copy link
Author

cypreess commented Mar 4, 2019

  1. Readability counts.

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

2 participants