diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst index c4f16f4404963..c34c9779e12ec 100644 --- a/doc/whats_new/v1.1.rst +++ b/doc/whats_new/v1.1.rst @@ -113,6 +113,10 @@ Changelog :pr:`20880` by :user:`Guillaume Lemaitre ` and :user:`AndrĂ¡s Simon `. +- |Enhancement| :func:`utils.estimator_html_repr` shows a more helpful error + message when running in a jupyter notebook that is not trusted. :pr:`21316` + by `Thomas Fan`_. + Code and Documentation Contributors ----------------------------------- diff --git a/sklearn/utils/_estimator_html_repr.py b/sklearn/utils/_estimator_html_repr.py index b2d38b9e97ab3..1f5c339c12771 100644 --- a/sklearn/utils/_estimator_html_repr.py +++ b/sklearn/utils/_estimator_html_repr.py @@ -309,6 +309,9 @@ def _write_estimator_html( display: inline-block; position: relative; } +#$id div.sk-text-repr-fallback { + display: none; +} """.replace( " ", "" ).replace( @@ -335,16 +338,33 @@ def estimator_html_repr(estimator): container_id = "sk-" + str(uuid.uuid4()) style_template = Template(_STYLE) style_with_id = style_template.substitute(id=container_id) + estimator_str = str(estimator) + + # The fallback message is shown by default and loading the CSS sets + # div.sk-text-repr-fallback to display: none to hide the fallback message. + # + # If the notebook is trusted, the CSS is loaded which hides the fallback + # message. If the notebook is not trusted, then the CSS is not loaded and the + # fallback message is shown by default. + # + # The reverse logic applies to HTML repr div.sk-container. + # div.sk-container is hidden by default and the loading the CSS displays it. + fallback_msg = ( + "Please rerun this cell to show the HTML repr or trust the notebook." + ) out.write( f"" f'
' - '
' + '
' + f"
{html.escape(estimator_str)}
{fallback_msg}" + "
" + '
") diff --git a/sklearn/utils/tests/test_estimator_html_repr.py b/sklearn/utils/tests/test_estimator_html_repr.py index f22c03f20bdd7..9d474ad10fe10 100644 --- a/sklearn/utils/tests/test_estimator_html_repr.py +++ b/sklearn/utils/tests/test_estimator_html_repr.py @@ -1,4 +1,5 @@ from contextlib import closing +import html from io import StringIO import pytest @@ -278,3 +279,14 @@ def test_one_estimator_print_change_only(print_changed_only): pca_repr = str(pca) html_output = estimator_html_repr(pca) assert pca_repr in html_output + + +def test_fallback_exists(): + """Check that repr fallback is in the HTML.""" + pca = PCA(n_components=10) + html_output = estimator_html_repr(pca) + + assert ( + f'
{html.escape(str(pca))}'
+        in html_output
+    )