Skip to content

Commit 56a98f0

Browse files
committed
fix membership tests for primitive values, closes #117
1 parent 6ad9367 commit 56a98f0

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

choicesenum/enums.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,23 @@
11
# coding: utf-8
22
from __future__ import absolute_import, unicode_literals
33

4-
from enum import Enum
4+
import six
5+
from enum import Enum, EnumMeta
56

67

7-
class ChoicesEnum(Enum):
8+
class ChoicesMetaClass(EnumMeta):
9+
10+
def __contains__(cls, member):
11+
if not isinstance(member, cls):
12+
try:
13+
member = cls(member)
14+
except Exception:
15+
return False
16+
17+
return member._name_ in cls._member_map_
18+
19+
20+
class ChoicesEnum(six.with_metaclass(ChoicesMetaClass, Enum)):
821

922
def __new__(cls, value, display=None):
1023
obj = object.__new__(cls)
@@ -90,7 +103,7 @@ def __json__(self):
90103

91104
@property
92105
def display(self):
93-
return self._display_ if self._display_ is not None else\
106+
return self._display_ if self._display_ is not None else \
94107
self._name_.replace('_', ' ').capitalize()
95108

96109
@property

tests/test_choicesenum.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,3 +296,9 @@ def test_should_return_default_value(colors):
296296
assert colors.get('#f00') == colors.RED
297297
assert colors.get('undefined_color') is None
298298
assert colors.get('undefined_color', colors.RED) == colors.RED
299+
300+
301+
def test_should_support_membership_vertification(colors):
302+
assert colors.RED in colors
303+
assert colors.RED.value in colors
304+
assert 'non-existent-color' not in colors

0 commit comments

Comments
 (0)