Skip to content

Commit e88e41c

Browse files
authored
Merge pull request #1163 from epiforecasts/fix/935-spurious-autoprint
Fix spurious printing of forecast/scores objects during :=
2 parents 99e9c0e + d91f6a1 commit e88e41c

6 files changed

Lines changed: 198 additions & 12 deletions

File tree

‎DESCRIPTION‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ LazyData: true
5656
Imports:
5757
checkmate,
5858
cli,
59-
data.table (>= 1.16.0),
59+
data.table (>= 1.17.0),
6060
ggplot2 (>= 3.4.0),
6161
lifecycle,
6262
methods,

‎NAMESPACE‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ S3method(get_pit_histogram,forecast_quantile)
4444
S3method(get_pit_histogram,forecast_sample)
4545
S3method(head,forecast)
4646
S3method(print,forecast)
47+
S3method(print,scores)
4748
S3method(score,default)
4849
S3method(score,forecast_binary)
4950
S3method(score,forecast_multivariate_point)

‎R/class-forecast.R‎

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -271,16 +271,22 @@ is_forecast <- function(x) {
271271
# where we used data.table := operator which will turn x into out before we
272272
# arrive to this function.
273273
is_dt_force_print <- identical(x, out) && ...length() == 1
274-
# ...length() as it still returns 1 in x[] and then skips validations in
275-
# undesired situation if we set ...length() > 1
274+
276275
# is.data.table: when [.data.table returns an atomic vector, it's clear it
277276
# cannot be a valid forecast object, and it is likely intended by the user
278277

279-
# in addition, we also check for a maximum length. The reason is that
280-
# print.data.table will internally subset the data.table before printing.
281-
# this subsetting triggers the validation, which is not desired in this case.
282-
# this is a hack and ideally, we'd do things differently.
283-
if (nrow(out) > 30 && is.data.table(out) && !is_dt_force_print) {
278+
if (is.data.table(out) && !is_dt_force_print) {
279+
# Validation (e.g. after a `:=` in-place modification) runs data.table
280+
# operations internally that overwrite data.table's autoprint-suppression
281+
# flag. data.table records the address of an object modified by `:=` in its
282+
# internal `.global$print`, and print.forecast() reads it via shouldPrint()
283+
# to suppress the spurious autoprint. We capture that state before
284+
# validating and restore it afterwards so `:=` keeps validating without
285+
# reintroducing the spurious print.
286+
# See https://github.com/epiforecasts/scoringutils/issues/935
287+
dt_global <- utils::getFromNamespace(".global", "data.table")
288+
suppress_autoprint <- identical(dt_global$print, data.table::address(out))
289+
284290
# check whether subset object passes validation
285291
validation <- try(
286292
assert_forecast(forecast = out, verbose = FALSE),
@@ -290,13 +296,16 @@ is_forecast <- function(x) {
290296
cli_warn(
291297
c(
292298
`!` = "Error in validating forecast object: {validation}.",
293-
i = "Note this error is sometimes related to `data.table`s `print`.
294-
Run {.help [{.fun assert_forecast}](scoringutils::assert_forecast)}
299+
i = "Run {.help [{.fun assert_forecast}](scoringutils::assert_forecast)}
295300
to confirm. To get rid of this warning entirely,
296301
call `as.data.table()` on the forecast object."
297302
)
298303
)
299304
}
305+
306+
if (suppress_autoprint) {
307+
dt_global$print <- data.table::address(out)
308+
}
300309
}
301310

302311
return(out)
@@ -408,6 +417,17 @@ tail.forecast <- function(x, ...) {
408417
#' print(dat)
409418
print.forecast <- function(x, ...) {
410419

420+
# Suppress autoprinting during data.table `:=` operations.
421+
# When `:=` modifies a data.table in place, R's autoprint mechanism triggers
422+
# the print method. data.table tracks this via an internal shouldPrint()
423+
# function which returns FALSE when `:=` was just used. We check this early
424+
# to avoid printing the forecast header in that case.
425+
# See https://github.com/epiforecasts/scoringutils/issues/935
426+
shouldPrint <- utils::getFromNamespace("shouldPrint", "data.table") # nolint: object_name_linter
427+
if (!shouldPrint(x)) {
428+
return(invisible(x))
429+
}
430+
411431
# get forecast type, forecast unit and score columns
412432
forecast_type <- try(
413433
do.call(get_forecast_type, list(forecast = x)),

‎R/class-scores.R‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,27 @@ assert_scores <- function(scores) {
7171
}
7272

7373

74+
#' @title Print a scores object
75+
#' @description
76+
#' Prints a `scores` object. Suppresses autoprinting during data.table
77+
#' `:=` operations by checking data.table's internal `shouldPrint()` flag.
78+
#' @param x A `scores` object
79+
#' @param ... Additional arguments for [print()].
80+
#' @returns Returns `x` invisibly.
81+
#' @export
82+
#' @keywords gain-insights
83+
print.scores <- function(x, ...) {
84+
# Suppress autoprinting during data.table `:=` operations.
85+
# See https://github.com/epiforecasts/scoringutils/issues/935
86+
shouldPrint <- utils::getFromNamespace("shouldPrint", "data.table") # nolint: object_name_linter
87+
if (!shouldPrint(x)) {
88+
return(invisible(x))
89+
}
90+
NextMethod()
91+
return(invisible(x))
92+
}
93+
94+
7495
#' @title Get names of the metrics that were used for scoring
7596
#' @description
7697
#' When applying a scoring rule via [score()], the names of the scoring rules

‎man/print.scores.Rd‎

Lines changed: 21 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎tests/testthat/test-class-forecast.R‎

Lines changed: 125 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,6 @@ test_that("print() throws the expected messages", {
155155
test <- data.table::copy(example_point)
156156
class(test) <- c("point", "forecast", "data.table", "data.frame")
157157

158-
# note that since introducing a length maximum for validation to be triggered,
159-
# we don't throw a warning automatically anymore
160158
suppressMessages(
161159
expect_message(
162160
capture.output(print(test)),
@@ -174,6 +172,131 @@ test_that("print() throws the expected messages", {
174172
})
175173

176174

175+
# ==============================================================================
176+
# Autoprint suppression during := operations (issue #935)
177+
# ==============================================================================
178+
179+
test_that(":= on forecast objects does not trigger spurious printing", {
180+
ex <- data.table::copy(example_quantile)
181+
output <- capture.output(ex[, model := paste(model, "a")])
182+
expect_identical(output, character(0))
183+
})
184+
185+
test_that(":= adding a new column to forecast objects does not print", {
186+
ex <- data.table::copy(example_quantile)
187+
output <- capture.output(ex[, new_col := "test"])
188+
expect_identical(output, character(0))
189+
})
190+
191+
test_that(":= on different forecast types does not trigger printing", {
192+
# Test across all forecast types to ensure the fix is comprehensive
193+
forecast_objects <- list(
194+
binary = data.table::copy(example_binary),
195+
quantile = data.table::copy(example_quantile),
196+
point = data.table::copy(example_point),
197+
sample_continuous = data.table::copy(example_sample_continuous),
198+
sample_discrete = data.table::copy(example_sample_discrete)
199+
)
200+
201+
for (name in names(forecast_objects)) {
202+
ex <- forecast_objects[[name]]
203+
output <- capture.output(ex[, model := paste(model, "a")])
204+
expect_identical(
205+
output, character(0),
206+
label = paste("Spurious printing for forecast type:", name)
207+
)
208+
}
209+
})
210+
211+
test_that("multiple sequential := operations do not trigger printing", {
212+
ex <- data.table::copy(example_quantile)
213+
output <- capture.output({
214+
ex[, model := paste(model, "a")]
215+
ex[, new_col1 := 1]
216+
ex[, new_col2 := "test"]
217+
})
218+
expect_identical(output, character(0))
219+
})
220+
221+
test_that("explicit print() still works after := suppression", {
222+
# After :=, data.table sets a flag that suppresses the next print.
223+
# In interactive R, autoprint consumes this flag. In non-interactive
224+
# contexts (testthat, scripts), we consume it manually with x[].
225+
ex <- data.table::copy(example_quantile)
226+
ex[, model := paste(model, "a")]
227+
invisible(capture.output(suppressMessages(ex[]))) # consume shouldPrint flag
228+
229+
output <- capture.output(suppressMessages(print(ex)))
230+
expect_gt(length(output), 0)
231+
})
232+
233+
test_that("print() on forecast objects still shows header and data", {
234+
ex <- as_forecast_quantile(na.omit(example_quantile))
235+
236+
messages <- capture.output(print(ex), type = "message")
237+
output <- capture.output(suppressMessages(print(ex)))
238+
239+
# Header should contain forecast type and unit info
240+
header_text <- paste(messages, collapse = " ")
241+
expect_true(grepl("Forecast type", header_text, fixed = TRUE))
242+
expect_true(grepl("Forecast unit", header_text, fixed = TRUE))
243+
244+
# Data should be printed
245+
expect_gt(length(output), 0)
246+
})
247+
248+
test_that("x[] force-print still works on forecast objects", {
249+
# x[] is data.table's force-print syntax, should still produce output
250+
ex <- as_forecast_quantile(na.omit(example_quantile))
251+
output <- capture.output(suppressMessages(ex[]))
252+
expect_gt(length(output), 0)
253+
})
254+
255+
test_that(":= on scores objects does not trigger spurious printing", {
256+
scores <- score(example_quantile)
257+
output <- capture.output(scores[, test := 3])
258+
expect_identical(output, character(0))
259+
})
260+
261+
test_that(":= that breaks the forecast contract still validates", {
262+
# Validation must keep running during in-place `:=` modification: removing a
263+
# required column should warn, even though the autoprint stays suppressed.
264+
ex <- as_forecast_quantile(na.omit(example_quantile))
265+
expect_warning(
266+
ex[, observed := NULL],
267+
"Error in validating"
268+
)
269+
})
270+
271+
test_that(":= that breaks the contract does not trigger spurious printing", {
272+
# Restoring validation must not reintroduce the spurious autoprint from #935.
273+
ex <- as_forecast_quantile(na.omit(example_quantile))
274+
output <- capture.output(
275+
suppressWarnings(ex[, observed := NULL])
276+
)
277+
expect_identical(output, character(0))
278+
})
279+
280+
test_that("[.forecast() validates subsets regardless of size", {
281+
# After removing the 30-row hack, validation should trigger for
282+
# any size subset that breaks the forecast contract
283+
test <- na.omit(data.table::copy(example_quantile))
284+
285+
# Small subset (previously skipped validation due to nrow <= 30 hack)
286+
small_test <- test[1:20]
287+
expect_warning(
288+
local(small_test[, colnames(small_test) != "observed", with = FALSE]),
289+
"Error in validating"
290+
)
291+
292+
# Large subset (was already validated before)
293+
expect_warning(
294+
local(test[, colnames(test) != "observed", with = FALSE]),
295+
"Error in validating"
296+
)
297+
})
298+
299+
177300
# ==============================================================================
178301
# check_number_per_forecast() # nolint: commented_code_linter
179302
# ==============================================================================

0 commit comments

Comments
 (0)