Marshmallow Enum Field
marshmallow-enum provides a dedicated `EnumField` for Marshmallow schemas, enabling seamless serialization and deserialization of Python `enum.Enum` members. It ensures type safety and proper validation when working with enumeration types in your API payloads. The current version is 1.5.1, and it typically follows the Marshmallow release cycle for compatibility updates, with minor releases as needed.
Warnings
- breaking The default behavior of `EnumField` regarding `by_value` and `by_name` changed significantly in version 1.0.0. Before 1.0.0, the default was `by_value=True`. From 1.0.0 onwards, if neither `by_value` nor `by_name` is explicitly set, it attempts to load by value first, then by name.
- gotcha When neither `by_value` nor `by_name` is explicitly specified for `EnumField`, it will attempt to deserialize by the enum member's value first, and if that fails, then by the member's name. This implicit behavior can lead to unexpected results if your enum values or names overlap with other valid inputs.
- gotcha If you are using `marshmallow-enum` with Marshmallow 3+, ensure you are correctly handling validation errors. Marshmallow 3 defaults to `unknown=EXCLUDE` for `Schema` which means unexpected fields are ignored, but invalid enum values will still raise validation errors. Misconfiguring `unknown` on the schema level can mask or misdirect issues.
Install
-
pip install marshmallow-enum
Imports
- EnumField
from marshmallow_enum import EnumField
Quickstart
import enum
from marshmallow import Schema, fields
from marshmallow_enum import EnumField
class Color(enum.Enum):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
class ItemSchema(Schema):
name = fields.String(required=True)
color = EnumField(Color, by_value=True, required=True)
# Example usage:
schema = ItemSchema()
# Serialization (Python Enum to string/value)
item_obj = {'name': 'Apple', 'color': Color.RED}
serialized_data = schema.dump(item_obj)
print(f"Serialized: {serialized_data}")
# Expected: {'name': 'Apple', 'color': 'red'}
# Deserialization (string/value to Python Enum)
input_data = {'name': 'Sky', 'color': 'blue'}
deser_obj = schema.load(input_data)
print(f"Deserialized: {deser_obj['color'] == Color.BLUE}")
print(f"Deserialized Type: {type(deser_obj['color'])}")
# Expected: True
# Expected Type: <enum 'Color'>