Python Enum with namedtuple

I saw a question asking how to do enum in Python and because I just learned about namedtuple I thought it should be an easy thing to do.

For an enum starting with 0, you can write it like this:

from collections import namedtuple as ntup

animalnames = 'Dog','Cat','Mouse','Horse','Bunny'

Animal = ntup('Enum', animalnames)._make(range(len(animalnames)))

Then you can

print Animal.Horse

and get 3 returned.
Also, because it is also a tuple, you can access it by the index:

Animal.Horse == Animal[3]

For an enum starting at 1 or higher there are a few ways.
You can use arange and add an offset:

from numpy import arange
animalnames = 'Dog','Cat','Mouse','Horse','Bunny'
Animal = ntup('Enum', animalnames)._make(3+arange(len(animalnames)))

Or stay with range:

animalnames = 'Dog','Cat','Mouse','Horse','Bunny'
Animal = ntup('Enum', animalnames)._make(range(3,3+len(animalnames)))

What is be nice about using this method is that it is still a tuple. Here are few lines and their output:

print Animal
print Animal._fields
print Animal[:]
print list(Animal)
print zip(Animal._fields, Animal)
Enum(Dog=3, Cat=4, Mouse=5, Horse=6, Bunny=7)
('Dog', 'Cat', 'Mouse', 'Horse', 'Bunny')
(3, 4, 5, 6, 7)
[3, 4, 5, 6, 7]
[('Dog', 3), ('Cat', 4), ('Mouse', 5), ('Horse', 6), ('Bunny', 7)]

Leave a comment