Created
April 21, 2021 12:38
-
-
Save DerMitch/ddaf351888a4baec13d752cd9bf9b1a9 to your computer and use it in GitHub Desktop.
Python Serde EnumField
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
from serde import fields, Model | |
from serde.exceptions import ValidationError | |
class EnumField(fields.Field): | |
""" | |
A field that can hold the value of an `enum.Enum`. | |
Args: | |
type: the concrete `Enum` this field can hold. | |
**kwargs: keyword arguments for the `Field` constructor. | |
""" | |
def __init__(self, enum=None, **kwargs): | |
""" | |
Create a new `EnumField`. | |
""" | |
if not issubclass(enum, Enum): | |
raise TypeError( | |
"First argument to EnumField must be a subclass of enum.Enum") | |
super().__init__(**kwargs) | |
self.enum = enum | |
def validate(self, value): | |
super().validate(value) | |
if not isinstance(value, self.enum): | |
raise ValidationError( | |
"Expected an instance of {}, but got {} instead".format( | |
self.enum, type(value)), | |
value=value | |
) | |
def serialize(self, value): | |
""" | |
Serialize the given value. | |
""" | |
return value.value | |
def deserialize(self, value): | |
""" | |
Deserialize the given value. | |
""" | |
return self.enum[value] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment