Skip to content

Commit fcca08e

Browse files
wimglennmdickinson
andauthored
gh-119594: Improve pow(fraction.Fraction(), b, modulo) error message (#119593)
If one calls pow(fractions.Fraction, x, module) with modulo not None, the error message now says that the types are incompatible rather than saying pow only takes 2 arguments. Implemented by having fractions.Fraction __pow__ accept optional modulo argument and return NotImplemented if not None. pow() then raises with appropriate message. --------- Co-authored-by: Mark Dickinson <[email protected]>
1 parent bf4ff3a commit fcca08e

File tree

3 files changed

+10
-1
lines changed

3 files changed

+10
-1
lines changed

Lib/fractions.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -848,14 +848,16 @@ def _mod(a, b):
848848

849849
__mod__, __rmod__ = _operator_fallbacks(_mod, operator.mod, False)
850850

851-
def __pow__(a, b):
851+
def __pow__(a, b, modulo=None):
852852
"""a ** b
853853
854854
If b is not an integer, the result will be a float or complex
855855
since roots are generally irrational. If b is an integer, the
856856
result will be rational.
857857
858858
"""
859+
if modulo is not None:
860+
return NotImplemented
859861
if isinstance(b, numbers.Rational):
860862
if b.denominator == 1:
861863
power = b.numerator

Lib/test/test_fractions.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1633,6 +1633,12 @@ def test_complex_handling(self):
16331633
message % ("divmod()", "complex", "Fraction"),
16341634
divmod, b, a)
16351635

1636+
def test_three_argument_pow(self):
1637+
message = "unsupported operand type(s) for ** or pow(): '%s', '%s', '%s'"
1638+
self.assertRaisesMessage(TypeError,
1639+
message % ("Fraction", "int", "int"),
1640+
pow, F(3), 4, 5)
1641+
16361642

16371643
if __name__ == '__main__':
16381644
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
If one calls pow(fractions.Fraction, x, module) with modulo not None, the error message now says that the types are incompatible rather than saying pow only takes 2 arguments. Patch by Wim Jeantine-Glenn and Mark Dickinson.

0 commit comments

Comments
 (0)