Pass enum to ndb.Model field in python
Question: I find [What's the best way to implement an 'enum' in
Python?](http://stackoverflow.com/questions/36932/whats-the-best-way-to-
implement-an-enum-in-python) for how to create enum in python. I have a field
in my `ndb.Model` that I want to accept one of my enum values. Do I simply set
the field to `StringProperty`? My enum is

    
    
    def enum(**enums):
        return type('Enum', (), enums)
    
    ALPHA = enum(A="A", B="B", C="C", D="D")
    


Answer: This is fully supported in the [ProtoRPC Python
API](https://developers.google.com/appengine/docs/python/tools/protorpc/) and
it's not worth rolling your own.

A simple Enum would look like the following:

    
    
    from protorpc import messages 
    
    class Alpha(messages.Enum):
        A = 0
        B = 1
        C = 2
        D = 3
    

As it turns out, `ndb` has `msgprop` module for storing `protorpc` objects and
this is
[documented](https://developers.google.com/appengine/docs/python/ndb/properties#msgprop).

So to store your `Alpha` enum, you'd do the following:

    
    
    from google.appengine.ext import ndb
    from google.appengine.ext.ndb import msgprop
    
    class Part(ndb.Model):
        alpha = msgprop.EnumProperty(Alpha, required=True)
        ...
    

**EDIT** : As pointed out by
[hadware](http://stackoverflow.com/users/1327143/hadware), a
`msgprop.EnumProperty` is not indexed by default. If you want to perform
queries over such properties you'd need to define the property as

    
    
        alpha = msgprop.EnumProperty(Alpha, required=True, indexed=True)
    

and then perform queries

    
    
    ndb.query(Part.alpha == Alpha.B)
    

or use any value other than `Alpha.B`.

