Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-100488: Add is_integer method to fractions.Fraction #100489

Merged
merged 3 commits into from
Jan 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Doc/library/fractions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,10 @@ def from_decimal(cls, dec):
(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.

Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,19 @@ def testFromDecimal(self):
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))
Expand Down
Original file line number Diff line number Diff line change
@@ -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`.