Skip to content

Instantly share code, notes, and snippets.

@Xorcerer
Last active August 29, 2015 14:02
Show Gist options
  • Save Xorcerer/18a6c2d514a3503c1b60 to your computer and use it in GitHub Desktop.
Save Xorcerer/18a6c2d514a3503c1b60 to your computer and use it in GitHub Desktop.
3 ways to create enum in python 2.x
# -*- coding: utf-8 -*-
# 普通程序员
RED = 'red'
BLUE = 'blue'
# 文艺程序员
def create_enum(name, members):
return type(name, (object,), {m.upper(): m for m in members})
# Usage:
def usage():
Color = create_enum('Color', ['red', 'blue'])
# Or
class Color(create_enum('Color', ['red', 'blue'])):
pass
# 2B程序员
class TrySetEnumException(Exception):
pass
class EnumAttribute(object):
def __init__(self, value):
self.value = value
def __get__(self, obj, type_):
return self.value
def __set__(self, obj, value):
print obj, value
raise TrySetEnumException()
def __delete__(self, obj):
raise TrySetEnumException()
def create_enum2(name, members):
member_dict = {m.upper(): EnumAttribute(m) for m in members}
return type(name, (object,), member_dict)()
from nose.tools import raises
def test():
Color = create_enum2('Color', ['red', 'blue'])
@raises(TrySetEnumException)
def f():
Color.RED = 1
f()
@raises(TrySetEnumException)
def g():
del Color.RED
g()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment