forked from cool-RR/python_toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcute_enum.py
More file actions
56 lines (39 loc) · 1.72 KB
/
cute_enum.py
File metadata and controls
56 lines (39 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
import enum
import functools
from python_toolbox import caching
class EnumType(enum.EnumMeta):
'''Metaclass for our kickass enum type.'''
def __dir__(cls):
# working around Python bug 22506 that would be fixed in Python 3.5.
return type.__dir__(cls) + cls._member_names_
__getitem__ = lambda self, i: self._values_tuple[i]
# This `__getitem__` is important, so we could feed enum types straight
# into `ProductSpace`.
_values_tuple = caching.CachedProperty(tuple)
@functools.total_ordering
class _OrderableEnumMixin:
'''
Mixin for an enum that has an order between items.
We're defining a mixin rather than defining these things on `CuteEnum`
because we can't use `functools.total_ordering` on `Enum`, because `Enum`
has exception-raising comparison methods, so `functools.total_ordering`
doesn't override them.
'''
number = caching.CachedProperty(
lambda self: type(self)._values_tuple.index(self)
)
__lt__ = lambda self, other: isinstance(other, CuteEnum) and \
(self.number < other.number)
class CuteEnum(_OrderableEnumMixin, enum.Enum, metaclass=EnumType):
'''
An improved version of Python's builtin `enum.Enum` type.
`CuteEnum` provides the following benefits:
- Each item has a property `number` which is its serial number in the
enum.
- Items are comparable with each other based on that serial number. So
sequences of enum items can be sorted.
- The enum type itself can be accessed as a sequence, and you can access
its items like this: `MyEnum[7]`.
'''