Thursday, September 22, 2011

Enums in Python

As it stands right now, there is no built in functions for enums in Python like there are in many other programming and scripting languages. Enum’s come in handy when you need to set flags or quickly compare objects. A quick search came up with a class and a function that pretty much emulates Enums inside of python. I’ve already started using it in my TCP/IP project I’m working on and it’s working great. Wish I would have found this sooner. Pretty soon I’ll be posting a quick little walk-through of sockets and TCP/IP in python that uses the enum example below. In the past couple of weeks I’ve come to see the huge potential of using sockets in tools, but I’ll cover all that in a different post.

def M_add_class_attribs(attribs):
def foo(name, bases, dict_):
for v, k in attribs:
dict_[k] = v
return type(name, bases, dict_)
return foo

def enum(names):
class Foo(object):
__metaclass__ = M_add_class_attribs(enumerate(names))
def __setattr__(self, name, value): # this makes it read-only
raise NotImplementedError
return Foo()

# Message Type Enum
message_types = enum(("MESSAGE", "STATUS", "NONE"))

# Check the message type against a member of the enum
if (message_type == message_types.MESSAGE):

No comments:

Post a Comment