Skip to content

gh-84978: expose __float__ dunder method as as_float #110460

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

Closed
wants to merge 1 commit into from
Closed
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
4 changes: 4 additions & 0 deletions Doc/library/operator.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 6 additions & 1 deletion Lib/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -432,6 +436,7 @@ def ixor(a, b):
__call__ = call
__floordiv__ = floordiv
__index__ = index
__float__ = as_float
__inv__ = inv
__invert__ = invert
__lshift__ = lshift
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Expose :meth:`~object.__float__` as :func:`operator.as_float`. Patch by
Sergey B Kirpichev.