Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Fix docstring typo; exclude buffers
  • Loading branch information
mdickinson committed May 28, 2020
commit ef94333cb57763bdb949aaf42a76d0fff481104d
2 changes: 1 addition & 1 deletion Doc/library/operator.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ The mathematical and bitwise operations are the most numerous:

.. function:: as_float(a)

Return *a* converted to an float. Equivalent to ``float(a)``, except
Return *a* converted to a float. Equivalent to ``float(a)``, except
that conversion from a string or bytestring is not permitted. The result
always has exact type :class:`float`.

Expand Down
16 changes: 14 additions & 2 deletions Lib/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,20 @@ def as_float(obj):

Same as float(obj), but does not accept strings.
"""
if isinstance(obj, (str, bytes, bytearray)):
raise TypeError("as_float argument must be numeric")
# Exclude strings and anything exposing the buffer interface.
bad_type = False
if isinstance(obj, str):
bad_type = True
else:
try:
memoryview(obj)
bad_type = True
except TypeError:
pass

if bad_type:
raise TypeError(f"must be real number, not {obj.__class__.__name__}")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean real number in the math sense? Or do you mean it as instead of a string representation of a number?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the mathematical sense. But this wording isn't new to this PR; it's copied from here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. That makes sense. :-)


return float(obj)

def floordiv(a, b):
Expand Down
7 changes: 6 additions & 1 deletion Lib/test/test_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,12 @@ def __index__(self):
self.assertIsFloatWithValue(operator.as_float(Confused()), 123.456)

# Not convertible.
bad_values = ["123", b"123", bytearray(b"123"), None, 1j]
import array

bad_values = [
"123", b"123", bytearray(b"123"), None, 1j,
array.array('B', b"123.0"),
]
for bad_value in bad_values:
with self.subTest(bad_value=bad_value):
with self.assertRaises(TypeError):
Expand Down