diff --git a/Doc/library/operator.rst b/Doc/library/operator.rst index 57c67bcf3aa12e..370858a79a271c 100644 --- a/Doc/library/operator.rst +++ b/Doc/library/operator.rst @@ -116,6 +116,10 @@ The mathematical and bitwise operations are the most numerous: The result always has exact type :class:`int`. Previously, the result could have been an instance of a subclass of ``int``. +.. function:: as_float(a) + __float__(a) + + Return *a* converted to a float. Equivalent to ``a.__float__()``. .. function:: inv(obj) invert(obj) diff --git a/Lib/operator.py b/Lib/operator.py index 30116c1189a499..fb5120b30cfbb6 100644 --- a/Lib/operator.py +++ b/Lib/operator.py @@ -10,7 +10,7 @@ This is the pure Python implementation of the module. """ -__all__ = ['abs', 'add', 'and_', 'attrgetter', 'call', 'concat', 'contains', 'countOf', +__all__ = ['abs', 'add', 'and_', 'attrgetter', 'as_float', 'call', 'concat', 'contains', 'countOf', 'delitem', 'eq', 'floordiv', 'ge', 'getitem', 'gt', 'iadd', 'iand', 'iconcat', 'ifloordiv', 'ilshift', 'imatmul', 'imod', 'imul', 'index', 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irshift', @@ -88,6 +88,10 @@ def index(a): "Same as a.__index__()." return a.__index__() +def as_float(a): + "Same as a.__float__()." + return a.__float__() + def inv(a): "Same as ~a." return ~a @@ -432,6 +436,7 @@ def ixor(a, b): __call__ = call __floordiv__ = floordiv __index__ = index +__float__ = as_float __inv__ = inv __invert__ = invert __lshift__ = lshift diff --git a/Lib/test/test_operator.py b/Lib/test/test_operator.py index 1db738d228b1b9..ded6360f8a7315 100644 --- a/Lib/test/test_operator.py +++ b/Lib/test/test_operator.py @@ -142,6 +142,14 @@ def test_add(self): self.assertRaises(TypeError, operator.add, None, None) self.assertEqual(operator.add(3, 4), 7) + def test_as_float(self): + from fractions import Fraction as F + + operator = self.module + self.assertRaises(TypeError, operator.as_float) + self.assertRaises(AttributeError, operator.as_float, None) + self.assertEqual(operator.as_float(F(1, 2)), 0.5) + def test_bitwise_and(self): operator = self.module self.assertRaises(TypeError, operator.and_) diff --git a/Misc/NEWS.d/next/Library/2023-10-06-09-36-06.gh-issue-84978.WVF04J.rst b/Misc/NEWS.d/next/Library/2023-10-06-09-36-06.gh-issue-84978.WVF04J.rst new file mode 100644 index 00000000000000..7e6a091aff6a57 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-10-06-09-36-06.gh-issue-84978.WVF04J.rst @@ -0,0 +1,2 @@ +Expose :meth:`~object.__float__` as :func:`operator.as_float`. Patch by +Sergey B Kirpichev.