PynamoDB
PynamoDB copied to clipboard
Support enumerations with EnumAttribute [enhancement proposal]
Is it a good idea to introduce a PR for this?
Enhancement: constrain attribute values by referencing an Enum
class.
Consider an e-commerce order status enumeration like:
import enum
class OrderStatus(enum.Enum):
RECEIVED = 1
PAYMENT_FAILED = 2
PROCESSING = 3
SHIPPED = 4
DELIVERED = 5
If a model has an order_status
attribute, we can constrain its values to OrderStatus
enumeration. Something like:
import pynamodb.models
from pynamodb.attributes import EnumAttribute
class OrderModel(pynamodb.models.Model):
order_status = EnumAttribute(enumeration=OrderStatus)
Usage cases:
Instantiating a model
my_order = OrderModel(order_status=OrderStatus.PROCESSING)
# Or:
my_order = OrderModel(order_status=3)
Assigning new value to order_status
my_order.order_status = OrderStatus.DELIVERED
# Or:
my_order.order_status = 5
Prevent assigning invalid values:
my_order.order_status = 9
Traceback (most recent call last):
...
EnumAttributeValueError: 9 is not a valid OrderStatus
Alternative ideas
Instead of introducing a new EnumAttribute
class, we could also modify NumberAttribute
and UnicodeAttribute
to support enumerations.
It seems to me, though, that creating a dedicated class will render better design and reduce risks of backwards incompatibility and of introducing bugs in the current code base.
- There
IntegerEnumAttribute
implemented in https://github.com/lyft/pynamodb-attributes. Perhaps that'll be a better place to start from? - At some point in the core library's evolution we've decided to keep features which don't map to core DynamoDB concepts out of it -- see https://github.com/pynamodb/PynamoDB/blob/master/docs/contributing.rst#the-scope-of-the-library. That's why we're adding them to an auxiliary library rather than to pynamodb.
p.s. it'll be good to move github.com/lyft/pynamodb-attributes to the pynamodb org @garrettheel ?
Wasn't aware of this repo, thanks for pointing out @ikonst
Looks like IntegerEnumAttribute
and UnicodeEnumAttribute
do exactly what I was looking for.
Perhaps we can reference these Attribute "add-ons" in the documentation? I searched for "enumeration" there and found nothing.
I'd be glad to send a PR for this documentation addition.
Might make sense to mention this library somewhere where we list attribute classes, though I wouldn't want PynamoDB docs to be the catalog of what pynamodb-attributes offers.