Skip to content

Commit 8842eb5

Browse files
tarun-227claude
andcommitted
[BUG] fix bare print on non-convergence and malformed ValueError format
- Replace `print("did not converge")` with `warnings.warn()` so that non-convergence is surfaced through Python's warning system instead of printing to stdout. This allows users to filter/capture the message programmatically. - Fix string formatting bug in `_estimate_GCV_UBRE` where `format(gamma)` was passed as a separate argument to `ValueError` instead of being interpolated into the message string, resulting in a confusing tuple error message like `('msg {}', '0.5')`. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent b6a48ab commit 8842eb5

2 files changed

Lines changed: 31 additions & 3 deletions

File tree

pygam/pygam.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -818,7 +818,11 @@ def _pirls(self, X, Y, weights):
818818
if diff < self.tol:
819819
return
820820

821-
print("did not converge")
821+
warnings.warn(
822+
"PIRLS did not converge."
823+
" Try increasing max_iter or decreasing tol.",
824+
stacklevel=2,
825+
)
822826
return
823827

824828
def _on_loop_start(self, variables):
@@ -1194,8 +1198,7 @@ def _estimate_GCV_UBRE(
11941198
"""
11951199
if gamma < 1:
11961200
raise ValueError(
1197-
"gamma scaling should be greater than 1, but found gamma = {}",
1198-
format(gamma),
1201+
f"gamma scaling should be greater than 1, but found gamma = {gamma}"
11991202
)
12001203

12011204
if modelmat is None:

pygam/tests/test_GAM_methods.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,31 @@ def test_fit_quantile_NOT_close_enough(head_circumference_X_y):
467467
assert np.abs(ratio - quantile) > tol
468468

469469

470+
def test_non_convergence_emits_warning(mcycle_X_y):
471+
"""Non-convergence should emit a warning, not print to stdout."""
472+
X, y = mcycle_X_y
473+
gam = LinearGAM(max_iter=1, tol=1e-100)
474+
import warnings
475+
476+
with warnings.catch_warnings(record=True) as w:
477+
warnings.simplefilter("always")
478+
gam.fit(X, y)
479+
convergence_warnings = [
480+
x for x in w if "did not converge" in str(x.message)
481+
]
482+
assert len(convergence_warnings) == 1
483+
484+
485+
def test_GCV_UBRE_gamma_error_message(mcycle_X_y, mcycle_gam):
486+
"""ValueError for gamma < 1 should have a properly formatted message."""
487+
with pytest.raises(ValueError, match=r"gamma.*0\.5"):
488+
mcycle_gam._estimate_GCV_UBRE(
489+
y=mcycle_X_y[1],
490+
modelmat=mcycle_gam._modelmat(mcycle_X_y[0]),
491+
gamma=0.5,
492+
)
493+
494+
470495
def test_fit_quantile_raises_ValueError(head_circumference_X_y):
471496
"""see that we DO NOT get fit on bad argument requests"""
472497
X, y = head_circumference_X_y

0 commit comments

Comments
 (0)