From e83f88a455261ed53530a960f1514ab7af7d2e82 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Sun, 1 Jan 2023 02:44:48 -0600 Subject: gh-100488: Add is_integer method to fractions.Fraction (#100489) --- Doc/library/fractions.rst | 6 ++++++ Lib/fractions.py | 4 ++++ Lib/test/test_fractions.py | 13 +++++++++++++ .../Library/2022-12-24-04-13-54.gh-issue-100488.Ut8HbE.rst | 1 + 4 files changed, 24 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2022-12-24-04-13-54.gh-issue-100488.Ut8HbE.rst 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`. -- cgit v0.12