From fcb508f07fba7060a6d717936ecf29bbb295522b Mon Sep 17 00:00:00 2001 From: Holger Frey Date: Thu, 6 Jul 2023 10:04:43 +0200 Subject: [PATCH] the method `Regression.predict()` requires 'x' or 'y' as keyword argument only --- linear_regression.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/linear_regression.py b/linear_regression.py index 2ff3a81..2e8d223 100644 --- a/linear_regression.py +++ b/linear_regression.py @@ -19,13 +19,13 @@ class Regression: def r2(self) -> float: return self.score - def predict(self, x: int | float = None, y: int | float = None) -> float: + def predict(self, *, x: int | float = None, y: int | float = None) -> float: """predict a value if x or y is given""" if x is not None: return self.intercept + x * self.coefficient if y is not None: return (y - self.intercept) / self.coefficient - msg = "predict() expects 1 argument, got 0" + msg = "predict() expects a keyword argument 'x' or 'y'" raise TypeError(msg) def to_dict(self): @@ -65,14 +65,21 @@ def test_linear_regression(example_data): def test_regression_predict(example_data): regression = linear_regression(example_data, x="A", y="B") - prediction = regression.predict(10) + prediction = regression.predict(x=10) assert pytest.approx(30.7) == prediction assert pytest.approx(10) == regression.predict(y=prediction) - with pytest.raises(TypeError, match="expects 1 argument"): + +def test_regression_predict_exceptions(example_data): + regression = linear_regression(example_data, x="A", y="B") + + with pytest.raises(TypeError, match="expects a keyword"): regression.predict() + with pytest.raises(TypeError, match="takes 1 positional argument but"): + regression.predict(1) + def test_regression_to_dict(example_data): regression = linear_regression(example_data, x="A", y="B")