Skip to content

Instantly share code, notes, and snippets.

@medwig
Last active May 14, 2024 15:55
Show Gist options
  • Save medwig/8ff559c9343e3d9db0cb773caf774112 to your computer and use it in GitHub Desktop.
Save medwig/8ff559c9343e3d9db0cb773caf774112 to your computer and use it in GitHub Desktop.
An enumerated type (enum) attribute for pynamodb
from pynamodb.models import Model
from pynamodb.constants import STRING
from pynamodb.attributes import UnicodeAttribute
ENUM = ('FOO', 'BAR', 'BAZ')
class EnumUnicodeAttribute(UnicodeAttribute):
"""
An enumerated unicode attribute
"""
attr_type = STRING
def serialize(self, value):
""" Raises ValueError if input value not in ENUM, otherwise continues as parent class """
if value not in ENUM:
raise ValueError(f"{self.attr_name} must be one of {ENUM}, not '{value}'")
else:
return UnicodeAttribute.serialize(self, value)
class Task(Model):
"""
A schema for an object in the Task table
"""
class Meta:
table_name = 'task-table'
status = EnumUnicodeAttribute()
@mmoss82
Copy link

mmoss82 commented Jan 13, 2022

from enum import Enum

class EnumUnicodeAttribute(UnicodeAttribute, Enum):
    """
    An enumerated unicode attribute
    """
    attr_type = STRING

    def serialize(self, value):
        """ Raises ValueError if input value not in ENUM, otherwise continues as parent class """
        if value not in [x.name for x in self]:
            raise ValueError(f"{self.attr_name} must be one of {[x.name for x in self]}, not '{value}'")
        else:
            return UnicodeAttribute.serialize(self, value)


class StatusAttribute(EnumUnicodeAttribute):
    Success = 1
    Fail = 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment