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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment