Repository: sphinx-gallery/sphinx-gallery

Issue:
BUG: Empty code block output
From @lucyleeow in https://github.com/matplotlib/matplotlib/issues/17479#issuecomment-717011368:

> Just looking into this, the problem with # sphinx_gallery_thumbnail_path is that it needs to be outside of the docstring, which makes it complicated for examples like annotation.py which is all docstring. Adding a code block under the docstring will work but will result in an empty code block at the end of the example.

@lucyleeow it seems like it would make sense to detect this case and not render it

Discussion:

Patch:
diff --git a/sphinx_gallery/gen_rst.py b/sphinx_gallery/gen_rst.py
index 0ed8582..3443e41 100644
--- a/sphinx_gallery/gen_rst.py
+++ b/sphinx_gallery/gen_rst.py
@@ -839,6 +839,11 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf,
             for label, content, line_number in script_blocks
         ]
 
+    # Remove final empty block, which can occur after config comments
+    # are removed
+    if script_blocks[-1][1].isspace():
+        script_blocks = script_blocks[:-1]
+
     if executable:
         clean_modules(gallery_conf, fname)
     output_blocks, time_elapsed = execute_script(script_blocks,


Test patch:
diff --git a/sphinx_gallery/tests/test_gen_rst.py b/sphinx_gallery/tests/test_gen_rst.py
index dccb334..443faff 100644
--- a/sphinx_gallery/tests/test_gen_rst.py
+++ b/sphinx_gallery/tests/test_gen_rst.py
@@ -451,6 +451,18 @@ def test_remove_config_comments(gallery_conf, req_pil):
     assert '# sphinx_gallery_thumbnail_number = 1' not in rst
 
 
+def test_final_empty_block(gallery_conf, req_pil):
+    """Test empty final block is removed. Empty final block can occur after
+    sole config comment is removed from final block."""
+    CONTENT.extend(
+        ('# %%', '', '# sphinx_gallery_line_numbers = True')
+    )
+    gallery_conf['remove_config_comments'] = True
+    rst = _generate_rst(gallery_conf, 'test.py', CONTENT)
+    want = "RuntimeWarning)\n\n\n.. rst-class:: sphx-glr-timing"
+    assert want in rst
+
+
 def test_download_link_note_only_html(gallery_conf, req_pil):
     """Test html only directive for download_link."""
     rst = _generate_rst(gallery_conf, 'test.py', CONTENT)