Skip to content

Commit d9378af

Browse files
authored
fix: insert_rows() accepts float column values as strings again (#824)
1 parent 42b66d3 commit d9378af

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

google/cloud/bigquery/_helpers.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import decimal
2020
import math
2121
import re
22+
from typing import Union
2223

2324
from google.cloud._helpers import UTC
2425
from google.cloud._helpers import _date_from_iso8601_date
@@ -338,14 +339,15 @@ def _int_to_json(value):
338339
return value
339340

340341

341-
def _float_to_json(value):
342+
def _float_to_json(value) -> Union[None, str, float]:
342343
"""Coerce 'value' to an JSON-compatible representation."""
343344
if value is None:
344345
return None
345-
elif math.isnan(value) or math.isinf(value):
346-
return str(value)
347-
else:
348-
return float(value)
346+
347+
if isinstance(value, str):
348+
value = float(value)
349+
350+
return str(value) if (math.isnan(value) or math.isinf(value)) else float(value)
349351

350352

351353
def _decimal_to_json(value):

tests/unit/test__helpers.py

+24
Original file line numberDiff line numberDiff line change
@@ -690,21 +690,45 @@ def _call_fut(self, value):
690690
def test_w_none(self):
691691
self.assertEqual(self._call_fut(None), None)
692692

693+
def test_w_non_numeric(self):
694+
with self.assertRaises(TypeError):
695+
self._call_fut(object())
696+
697+
def test_w_integer(self):
698+
result = self._call_fut(123)
699+
self.assertIsInstance(result, float)
700+
self.assertEqual(result, 123.0)
701+
693702
def test_w_float(self):
694703
self.assertEqual(self._call_fut(1.23), 1.23)
695704

705+
def test_w_float_as_string(self):
706+
self.assertEqual(self._call_fut("1.23"), 1.23)
707+
696708
def test_w_nan(self):
697709
result = self._call_fut(float("nan"))
698710
self.assertEqual(result.lower(), "nan")
699711

712+
def test_w_nan_as_string(self):
713+
result = self._call_fut("NaN")
714+
self.assertEqual(result.lower(), "nan")
715+
700716
def test_w_infinity(self):
701717
result = self._call_fut(float("inf"))
702718
self.assertEqual(result.lower(), "inf")
703719

720+
def test_w_infinity_as_string(self):
721+
result = self._call_fut("inf")
722+
self.assertEqual(result.lower(), "inf")
723+
704724
def test_w_negative_infinity(self):
705725
result = self._call_fut(float("-inf"))
706726
self.assertEqual(result.lower(), "-inf")
707727

728+
def test_w_negative_infinity_as_string(self):
729+
result = self._call_fut("-inf")
730+
self.assertEqual(result.lower(), "-inf")
731+
708732

709733
class Test_decimal_to_json(unittest.TestCase):
710734
def _call_fut(self, value):

0 commit comments

Comments
 (0)