Skip to content

Instantly share code, notes, and snippets.

@DerMitch
Created April 21, 2021 12:38
Show Gist options
  • Save DerMitch/ddaf351888a4baec13d752cd9bf9b1a9 to your computer and use it in GitHub Desktop.
Save DerMitch/ddaf351888a4baec13d752cd9bf9b1a9 to your computer and use it in GitHub Desktop.
Python Serde EnumField
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