diff options
-rw-r--r-- | Doc/library/fractions.rst | 6 | ||||
-rw-r--r-- | Lib/fractions.py | 4 | ||||
-rw-r--r-- | Lib/test/test_fractions.py | 13 | ||||
-rw-r--r-- | Misc/NEWS.d/next/Library/2022-12-24-04-13-54.gh-issue-100488.Ut8HbE.rst | 1 |
4 files changed, 24 insertions, 0 deletions
diff --git a/Doc/library/fractions.rst b/Doc/library/fractions.rst index c46d88b..dc9d5fc 100644 --- a/Doc/library/fractions.rst +++ b/Doc/library/fractions.rst @@ -117,6 +117,12 @@ another rational number, or from a string. .. versionadded:: 3.8 + .. method:: is_integer() + + Return ``True`` if the Fraction is an integer. + + .. versionadded:: 3.12 + .. classmethod:: from_float(flt) Alternative constructor which only accepts instances of diff --git a/Lib/fractions.py b/Lib/fractions.py index 75c7df1..4302f3f 100644 --- a/Lib/fractions.py +++ b/Lib/fractions.py @@ -225,6 +225,10 @@ class Fraction(numbers.Rational): (cls.__name__, dec, type(dec).__name__)) return cls(*dec.as_integer_ratio()) + def is_integer(self): + """Return True if the Fraction is an integer.""" + return self._denominator == 1 + def as_integer_ratio(self): """Return the integer ratio as a tuple. diff --git a/Lib/test/test_fractions.py b/Lib/test/test_fractions.py index 7fa9dbe..819d680 100644 --- a/Lib/test/test_fractions.py +++ b/Lib/test/test_fractions.py @@ -340,6 +340,19 @@ class FractionTest(unittest.TestCase): ValueError, "cannot convert NaN to integer ratio", F.from_decimal, Decimal("snan")) + def test_is_integer(self): + self.assertTrue(F(1, 1).is_integer()) + self.assertTrue(F(-1, 1).is_integer()) + self.assertTrue(F(1, -1).is_integer()) + self.assertTrue(F(2, 2).is_integer()) + self.assertTrue(F(-2, 2).is_integer()) + self.assertTrue(F(2, -2).is_integer()) + + self.assertFalse(F(1, 2).is_integer()) + self.assertFalse(F(-1, 2).is_integer()) + self.assertFalse(F(1, -2).is_integer()) + self.assertFalse(F(-1, -2).is_integer()) + def test_as_integer_ratio(self): self.assertEqual(F(4, 6).as_integer_ratio(), (2, 3)) self.assertEqual(F(-4, 6).as_integer_ratio(), (-2, 3)) diff --git a/Misc/NEWS.d/next/Library/2022-12-24-04-13-54.gh-issue-100488.Ut8HbE.rst b/Misc/NEWS.d/next/Library/2022-12-24-04-13-54.gh-issue-100488.Ut8HbE.rst new file mode 100644 index 0000000..f7c07c0 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2022-12-24-04-13-54.gh-issue-100488.Ut8HbE.rst @@ -0,0 +1 @@ +Add :meth:`Fraction.is_integer` to check whether a :class:`fractions.Fraction` is an integer. This improves duck type compatibility with :class:`float` and :class:`int`. |