Package flumotion :: Package common :: Module enum
[hide private]

Source Code for Module flumotion.common.enum

 1  # -*- Mode: Python; test-case-name: flumotion.test.test_enum -*- 
 2  # vi:si:et:sw=4:sts=4:ts=4 
 3  # 
 4  # Flumotion - a streaming media server 
 5  # Copyright (C) 2004,2005,2006,2007 Fluendo, S.L. (www.fluendo.com). 
 6  # All rights reserved. 
 7   
 8  # This file may be distributed and/or modified under the terms of 
 9  # the GNU General Public License version 2 as published by 
10  # the Free Software Foundation. 
11  # This file is distributed without any warranty; without even the implied 
12  # warranty of merchantability or fitness for a particular purpose. 
13  # See "LICENSE.GPL" in the source distribution for more information. 
14   
15  # Licensees having purchased or holding a valid Flumotion Advanced 
16  # Streaming Server license may use this file in accordance with the 
17  # Flumotion Advanced Streaming Server Commercial License Agreement. 
18  # See "LICENSE.Flumotion" in the source distribution for more information. 
19   
20  # Headers in this file shall remain intact. 
21   
22  """ 
23  Enum class implementation 
24  """ 
25   
26   
27 -class EnumMetaClass(type):
28 # pychecker likes this attribute to be there since we use it in this class 29 __enums__ = {} 30
31 - def __len__(self):
32 return len(self.__enums__)
33
34 - def __getitem__(self, value):
35 try: 36 return self.__enums__[value] 37 except KeyError: 38 raise StopIteration
39
40 - def __setitem__(self, value, enum):
41 self.__enums__[value] = enum 42 setattr(self, enum.name, enum)
43
44 -class Enum(object):
45 __metaclass__ = EnumMetaClass
46 - def __init__(self, value, name, nick=None):
47 self.value = value 48 self.name = name 49 50 if nick == None: 51 nick = name 52 53 self.nick = nick
54
55 - def __repr__(self):
56 return '<enum %s of type %s>' % (self.name, 57 self.__class__.__name__)
58
59 - def get(klass, value):
60 return klass.__enums__[value]
61 get = classmethod(get) 62
63 - def set(klass, value, item):
64 klass[value] = item
65 set = classmethod(set)
66
67 -class EnumClass(object):
68 - def __new__(klass, type_name, names=(), nicks=(), **extras):
69 if nicks: 70 if len(names) != len(nicks): 71 raise TypeError("nicks must have the same length as names") 72 else: 73 nicks = names 74 75 for extra in extras.values(): 76 if not isinstance(extra, tuple): 77 raise TypeError('extra must be a tuple, not %s' % type(extra)) 78 79 if len(extra) != len(names): 80 raise TypeError("extra items must have a length of %d" % 81 len(names)) 82 83 # we reset __enums__ to {} otherwise it retains the other registered 84 # ones 85 etype = EnumMetaClass(type_name, (Enum,), {'__enums__': {}}) 86 for value, name in enumerate(names): 87 enum = etype(value, name, nicks[value]) 88 for extra_key, extra_values in extras.items(): 89 assert not hasattr(enum, extra_key) 90 setattr(enum, extra_key, extra_values[value]) 91 etype[value] = enum 92 93 return etype
94