Skip to content
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
11 changes: 9 additions & 2 deletions Lib/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,9 +453,16 @@ def median_grouped(data, interval=1.0):
# Coerce to floats, raising a TypeError if not possible
try:
interval = float(interval)
except ValueError as exc:
raise TypeError(
f'interval must be a real number, got {interval!r}'
) from exc
try:
x = float(x)
except ValueError:
raise TypeError(f'Value cannot be converted to a float')
except ValueError as exc:
raise TypeError(
f'data sequence must contain real numbers, found {x!r}'
) from exc

# Interpolate the median using the formula found at:
# https://www.cuemath.com/data/median-of-grouped-data/
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -1799,6 +1799,25 @@ def test_data_type_error(self):
interval = b""
self.assertRaises(TypeError, self.func, data, interval)

def test_exception_chaining_and_messages(self):
# TypeError raised for bad interval should chain the original ValueError
# and identify the problematic parameter.
data = [1, 2, 3]
with self.assertRaises(TypeError) as cm:
self.func(data, interval="bad")
exc = cm.exception
self.assertIsInstance(exc.__cause__, ValueError)
self.assertIn("interval", str(exc))

# TypeError raised for non-numeric data should chain the original ValueError
# and identify that the data is the problem.
data = ["a", "b", "c"]
with self.assertRaises(TypeError) as cm:
self.func(data)
exc = cm.exception
self.assertIsInstance(exc.__cause__, ValueError)
self.assertIn("data", str(exc))


class TestMode(NumericTestCase, AverageMixin, UnivariateTypeMixin):
# Test cases for the discrete version of mode.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix :func:`statistics.median_grouped` to chain the original :exc:`ValueError`
when coercing *interval* or the median data value to ``float`` fails, and
improve the error message to identify which parameter caused the failure.
Loading