In the embedded world where C/C++ are the predominantly used languages, the enum data type is heavily used. It’s quick and easy to use and understand for specifying flags and register values. Not yet understanding that Python’s real strength is hash-able data types and that a switch statement didn’t exist, I found myself wanting to use traditional C/C++ enumerated data types when I first started learning Python.
Even though there is no “enum” keyword in Python, there are a few easy ways to create an enumerated data type. The following snippet uses the Python argument packer to create a new data type that is just a key value paired dictionary.
def enum(*args):
enums = dict(zip(args, range(len(args))))
return type('Enum', (), enums)
Thats it. This simple function takes a list of items and auto-completes the value. It can easily be used like the following.
alignment = enum("left","center","right")
def alignText(text, pos):
if pos == alignment.left:
pass
alignText("some text", alignment.left)
Another object oriented approach I came across is to overload the existing Python set( ) data type and override the __getattr__() method.
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
def __setattr__(self, name, value):
pass
def __delattr__(self, name):
pass
Neither approach fully addresses all the functionality of the C/C++ enum type. The missing functionality is the ability to specify a value for an entry and having all sequential entries be incremented by one (below). However, both solutions do offer a quick enumerated data type that can be used in most scenarios.
enum alignment = { LEFT, // 0
CENTER=10, // 10
RIGHT // 11
};