5
5
from enum import Enum , EnumMeta
6
6
7
7
8
+ def is_member_factory (enum_member ):
9
+ "Return a property that checks if the current enum is the expected one"
10
+ @property
11
+ def is_member (self ):
12
+ return self == enum_member
13
+ return is_member
14
+
15
+
8
16
class ChoicesMetaClass (EnumMeta ):
9
17
18
+ def __new__ (metacls , cls , bases , classdict ):
19
+ enum_class = EnumMeta .__new__ (metacls , cls , bases , classdict )
20
+ for name , enum_value in enum_class ._member_map_ .items ():
21
+ prop_name = 'is_{}' .format (name .lower ())
22
+ setattr (enum_class , prop_name , is_member_factory (enum_value ))
23
+
24
+ return enum_class
25
+
10
26
def __contains__ (cls , member ):
11
27
if not isinstance (member , cls ):
12
28
try :
@@ -25,13 +41,6 @@ def __new__(cls, value, display=None):
25
41
obj ._display_ = display
26
42
return obj
27
43
28
- def __getattr__ (self , item ):
29
- is_attr = 'is_'
30
- if item .startswith (is_attr ) and item in self ._get_dynamic_property_names ():
31
- search = item [len (is_attr ):]
32
- return search == self ._name_ .lower ()
33
- raise AttributeError ("'{}' object has no attribute '{}'" .format (type (self ).__name__ , item ))
34
-
35
44
def __str__ (self ):
36
45
return str (self .value )
37
46
@@ -75,14 +84,6 @@ def __gt__(self, other):
75
84
def __ge__ (self , other ):
76
85
return self .value >= self ._get_value (other )
77
86
78
- def __dir__ (self ):
79
- return sorted (set (
80
- dir (type (self )) +
81
- list (self .__dict__ .keys ()) +
82
- ['display' , 'get_choices' , ] +
83
- list (self ._get_dynamic_property_names ())
84
- ))
85
-
86
87
def __json__ (self ):
87
88
"""
88
89
If you want json serialization, you have at least two options:
@@ -114,14 +115,6 @@ def description(self):
114
115
"""
115
116
return self .display
116
117
117
- @classmethod
118
- def _get_dynamic_property_names (cls ):
119
- """
120
- Args:
121
- cls (Enum): Enum class.
122
- """
123
- return ('is_{}' .format (x ._name_ .lower ()) for x in cls )
124
-
125
118
@classmethod
126
119
def choices (cls ):
127
120
"""
0 commit comments