Nektar++
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
enum.py
Go to the documentation of this file.
1 # Proper enums in Python
2 # Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486
3 # Submitter: Zoran Isailovski
4 # Version: 1.6
5 # Updated: 2005/05/09
6 # License: http://www.python.org/psf/license/
7 
8 def Enum(*names):
9  ##assert names, "Empty enums are not supported" # <- Don't like empty enums? Uncomment!
10 
11  class EnumClass(object):
12  __slots__ = names
13  def __iter__(self): return iter(constants)
14  def __len__(self): return len(constants)
15  def __getitem__(self, i): return constants[i]
16  def __repr__(self): return 'Enum' + str(names)
17  def __str__(self): return 'enum ' + str(constants)
18 
19  class EnumValue(object):
20  __slots__ = ('__value')
21  def __init__(self, value): self.__value = value
22  Value = property(lambda self: self.__value)
23  EnumType = property(lambda self: EnumType)
24  def __hash__(self): return hash(self.__value)
25  def __cmp__(self, other):
26  # C fans might want to remove the following assertion
27  # to make all enums comparable by ordinal value {;))
28  assert self.EnumType is other.EnumType, "Only values from the same enum are comparable"
29  return cmp(self.__value, other.__value)
30  def __invert__(self): return constants[maximum - self.__value]
31  def __nonzero__(self): return bool(self.__value)
32  def __repr__(self): return str(names[self.__value])
33 
34  maximum = len(names) - 1
35  constants = [None] * len(names)
36  for i, each in enumerate(names):
37  val = EnumValue(i)
38  setattr(EnumClass, each, val)
39  constants[i] = val
40  constants = tuple(constants)
41  EnumType = EnumClass()
42  return EnumType
43 
44 
45 if __name__ == '__main__':
46  print '\n*** Enum Demo ***'
47  print '--- Days of week ---'
48  Days = Enum('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su')
49  print Days
50  print Days.Mo
51  print Days.Fr
52  print Days.Mo < Days.Fr
53  print list(Days)
54  for each in Days:
55  print 'Day:', each
56  print '--- Yes/No ---'
57  Confirmation = Enum('No', 'Yes')
58  answer = Confirmation.No
59  print 'Your answer is not', ~answer