Last active
August 29, 2015 14:02
-
-
Save Xorcerer/18a6c2d514a3503c1b60 to your computer and use it in GitHub Desktop.
3 ways to create enum in python 2.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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