Marshmallow Enum Field

1.5.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to define an `EnumField` in a Marshmallow schema. It uses `by_value=True` to specify that the enum should be serialized/deserialized by its member's value. The example shows both dumping (serializing) a Python `Enum` instance to a string and loading (deserializing) a string back into an `Enum` instance.

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'>

view raw JSON →