]> granicus.if.org Git - python/commitdiff
revert change 87a9dff5106c: pure Enum members again evaluate to True;
authorEthan Furman <ethan@stoneleaf.us>
Fri, 15 Jan 2016 23:01:33 +0000 (15:01 -0800)
committerEthan Furman <ethan@stoneleaf.us>
Fri, 15 Jan 2016 23:01:33 +0000 (15:01 -0800)
update Finer Points section of docs to cover boolean evaluation;
add more tests for pure and mixed boolean evaluation

Doc/library/enum.rst
Lib/enum.py
Lib/test/test_enum.py

index a76f5a369ca025f9df66bbb6832c815f001763ee..377ac3e245091ffdb8b6ce86444ee7b37bde2a94 100644 (file)
@@ -257,7 +257,7 @@ members are not integers (but see `IntEnum`_ below)::
     >>> Color.red < Color.blue
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
-    TypeError: '<' not supported between instances of 'Color' and 'Color'
+    TypeError: unorderable types: Color() < Color()
 
 Equality comparisons are defined though::
 
@@ -747,6 +747,15 @@ besides the :class:`Enum` member you looking for::
 
 .. versionchanged:: 3.5
 
+Boolean evaluation: Enum classes that are mixed with non-Enum types (such as
+:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
+type's rules; otherwise, all members evaluate as ``True``.  To make your own
+Enum's boolean evaluation depend on the member's value add the following to
+your class::
+
+    def __bool__(self):
+        return bool(self._value_)
+
 The :attr:`__members__` attribute is only available on the class.
 
 If you give your :class:`Enum` subclass extra methods, like the `Planet`_
index 35a9c779356220429a3ed16458bc4ab4880df5e0..ac89d6ba26ee7bba0f37039e70cbf9d82c86a13b 100644 (file)
@@ -482,9 +482,6 @@ class Enum(metaclass=EnumMeta):
     def __str__(self):
         return "%s.%s" % (self.__class__.__name__, self._name_)
 
-    def __bool__(self):
-        return bool(self._value_)
-
     def __dir__(self):
         added_behavior = [
                 m
index e4e6c2b51af23d6206561cb08eb88d39c8991e05..7985948041a922b8ab8b448fbe378fc7d8706574 100644 (file)
@@ -272,11 +272,26 @@ class TestEnum(unittest.TestCase):
                 _any_name_ = 9
 
     def test_bool(self):
+        # plain Enum members are always True
         class Logic(Enum):
             true = True
             false = False
         self.assertTrue(Logic.true)
-        self.assertFalse(Logic.false)
+        self.assertTrue(Logic.false)
+        # unless overridden
+        class RealLogic(Enum):
+            true = True
+            false = False
+            def __bool__(self):
+                return bool(self._value_)
+        self.assertTrue(RealLogic.true)
+        self.assertFalse(RealLogic.false)
+        # mixed Enums depend on mixed-in type
+        class IntLogic(int, Enum):
+            true = 1
+            false = 0
+        self.assertTrue(IntLogic.true)
+        self.assertFalse(IntLogic.false)
 
     def test_contains(self):
         Season = self.Season