rstudio / reticulate

R Interface to Python
https://rstudio.github.io/reticulate
Apache License 2.0
1.67k stars 327 forks source link

Support `results = 'hide'` directly in python engine #1599

Open cderv opened 4 months ago

cderv commented 4 months ago

Reported in

and full example at

Problem

Currently, results = 'hide' does not seem to be handled by reticulate's knitr engine. Example:

---
title: "Test report"
output: html_document
---

```{r, results = 'hide'}
class MyClass:
    def _repr_html_(self):
        return "<p>uh-oh</p>"

MyClass()


The results will still be shown. This is a minimal example - see https://github.com/posit-dev/great-tables/issues/291 for one with **great_tables**

## Context

This is because `_repr_html_` is catched to be returned as a `knitr::raw_html()`
https://github.com/rstudio/reticulate/blob/d4e752bf4e6f3970465f327581de1a7185624a1e/R/knitr-engine.R#L744-L750
and provided in the `out` component on which `knitr:::sew()` will apply
https://github.com/rstudio/reticulate/blob/d4e752bf4e6f3970465f327581de1a7185624a1e/R/knitr-engine.R#L626-L628

By returning `engine_output(out = )`, knitr's assumes the output is already filtered with what should be filtered.
Otherwise, it will be handled directly `engine_output()` default usage
https://github.com/yihui/knitr/blob/ba8d9fb0ecd60f3f9ebec58fdde1e689bdc40ad3/R/engine.R#L96-L98

So I do think **reticulate** needs to support `results = 'hide'` and not provide outputs in the list when the option is provided. 

I can make a PR - just need to think about the best place to do this. 
t-kalinowski commented 4 months ago

Thanks, I agree reticulate should support results = 'hide' option.

What is the relation or difference between include = FALSE and results = 'hide'? I believe that reticulate already has support for a include = FALSE chunk option.

cderv commented 4 months ago

include = FALSE means that chunks are ran, but nothing (nor source or results) is added to the output. This is directly handled by knitr for all engine as it will only show the processed output of an engine when include = TRUE.

results = "hide" means to hide the results in the outputs. echo = FALSE and results = "hide" together are almost equivalent to include = FALSE, except with includes, all the hooks will still apply (especially the output hooks). While for results is does not necessarily. But usually the hooks may not do any difference.

Anyhow, I don't think reticulate needs to handle include, but it needs to handle results. I'll send a PR.