Skip to content

Commit

Permalink
Fix the fraction module so that __rpow__ works on arbitrary classes.
Browse files Browse the repository at this point in the history
The fraction module implicitly casted float if __rpow__ was implemented in your class when raising a fraction to a power. Now it isn't done but will raise an exception if __rpow__ isn't implemented.
  • Loading branch information
zitterbewegung committed May 20, 2024
1 parent 1195c16 commit 1de7a44
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 4 deletions.
10 changes: 7 additions & 3 deletions Doc/library/functions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -608,9 +608,13 @@ are always available. They are listed here in alphabetical order.
will be used for both the global and the local variables. If *globals* and
*locals* are given, they are used for the global and local variables,
respectively. If provided, *locals* can be any mapping object. Remember
that at the module level, globals and locals are the same dictionary. If exec
gets two separate objects as *globals* and *locals*, the code will be
executed as if it were embedded in a class definition.
that at the module level, globals and locals are the same dictionary.

.. note::

Most users should just pass a *globals* argument and never *locals*.
If exec gets two separate objects as *globals* and *locals*, the code
will be executed as if it were embedded in a class definition.

If the *globals* dictionary does not contain a value for the key
``__builtins__``, a reference to the dictionary of the built-in module
Expand Down
4 changes: 3 additions & 1 deletion Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,8 +875,10 @@ def __pow__(a, b):
# A fractional power will generally produce an
# irrational number.
return float(a) ** float(b)
else:
elif isinstance(b, (float, complex)):
return float(a) ** b
else:
return NotImplemented

def __rpow__(b, a):
"""a ** b"""
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,7 @@ Kasun Herath
Chris Herborth
Ivan Herman
Jürgen Hermann
Joshua Jay Herman
Gary Herron
Ernie Hershey
Thomas Herve
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This fixes a situation where raising a class with rpow in the class calling
the exponent operator to raise it to the power of that class to not cast it
as a float.

0 comments on commit 1de7a44

Please sign in to comment.