Skip to content

Commit a465dad

Browse files
committed
BUG: Ensure Fraction.__bool__ returns a bool
Some numerator types used (specifically NumPy) decides to not return a python boolean for the `!=` operation. Using the equivalent call to `bool()` guarantees a bool return also for such types. Closes bpo-39274
1 parent dc0284e commit a465dad

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

Lib/fractions.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -647,7 +647,9 @@ def __ge__(a, b):
647647

648648
def __bool__(a):
649649
"""a != 0"""
650-
return a._numerator != 0
650+
# bpo-39274: Use bool() because (a._numerator != 0) can return an
651+
# object which is not a bool.
652+
return bool(a._numerator)
651653

652654
# support for pickling, copy, and deepcopy
653655

Lib/test/test_fractions.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import numbers
77
import operator
88
import fractions
9+
import functools
910
import sys
1011
import unittest
1112
import warnings
@@ -346,6 +347,42 @@ def testConversions(self):
346347

347348
self.assertTypedEquals(0.1+0j, complex(F(1,10)))
348349

350+
def testBoolGuarateesBoolReturn(self):
351+
# Ensure that __bool__ is used on numerator which guarantees a bool
352+
# return. See also bpo-39274.
353+
@functools.total_ordering
354+
class CustomValue:
355+
denominator = 1
356+
357+
def __init__(self, value):
358+
self.value = value
359+
360+
def __bool__(self):
361+
return bool(self.value)
362+
363+
@property
364+
def numerator(self):
365+
# required to preserve `self` during instantiation
366+
return self
367+
368+
def __eq__(self, other):
369+
raise AssertionError("Avoid comparisons in Fraction.__bool__")
370+
371+
__lt__ = __eq__
372+
373+
# We did not implement all abstract methods, so register:
374+
numbers.Rational.register(CustomValue)
375+
376+
numerator = CustomValue(1)
377+
r = F(numerator)
378+
# ensure the numerator was not lost during instantiation:
379+
self.assertIs(r.numerator, numerator)
380+
self.assertIs(bool(r), True)
381+
382+
numerator = CustomValue(0)
383+
r = F(numerator)
384+
self.assertIs(bool(r), False)
385+
349386
def testRound(self):
350387
self.assertTypedEquals(F(-200), round(F(-150), -2))
351388
self.assertTypedEquals(F(-200), round(F(-250), -2))
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``bool(fraction.Fraction)`` now returns a boolean even if (numerator != 0) does not return a boolean (ex: numpy number).

0 commit comments

Comments
 (0)