Skip to content

Fix: ipython directive skips execution inside excluded only blocks#15248

Closed
w1ndcn wants to merge 1 commit into
ipython:mainfrom
w1ndcn:w1ndcn/fix/sphinx-conditional-exec
Closed

Fix: ipython directive skips execution inside excluded only blocks#15248
w1ndcn wants to merge 1 commit into
ipython:mainfrom
w1ndcn:w1ndcn/fix/sphinx-conditional-exec

Conversation

@w1ndcn

@w1ndcn w1ndcn commented Jun 10, 2026

Copy link
Copy Markdown

Closes #9339

Problem

The ipython Sphinx directive executes code at the parse stage. When wrapped in a conditional directive like only with a false condition for the current builder, the code still runs:

.. only:: latex

   .. ipython::

      In [1]: dangerous_operation()

Building with html builder — the only:: latex condition is false, yet dangerous_operation() still executes. This is because Sphinx's only directive evaluates conditions at the post-transform stage, after all child directive run() methods have already been called.

Fix

Add _is_inside_excluded_only() to IPythonDirective. It walks up the parent node chain via self.state.parent, and if any ancestor is an only node whose expression evaluates to false for the current builder's tags, returns True. When true, run() returns [] early without executing code or calling setup/teardown.

Key insight: during nested_parse inside Only.run(), the only node is set as the parent in the docutils state machine, so self.state.parent is directly the only node — no fragile heuristics needed.

Changes

IPython/sphinxext/ipython_directive.py

  • IPythonDirective._is_inside_excluded_only(): walks parent chain, evaluates only node expressions against env.app.tags
  • IPythonDirective.run(): early return when inside an excluded only block

tests/test_ipython_directive.py (new)

  • test_only_excluded_skips_execution: only:: latex under html builder → code not executed
  • test_only_included_executes_normally: only:: html under html builder → code executed
  • test_nested_only_skips_execution: nested only:: html > only:: latex → inner block skipped

@w1ndcn w1ndcn changed the title Skip ipython directive execution inside excluded only blocks Fix: ipython directive skips execution inside excluded only blocks Jun 10, 2026
@w1ndcn

w1ndcn commented Jun 10, 2026

Copy link
Copy Markdown
Author

Renaming branch — recreating

@w1ndcn w1ndcn closed this Jun 10, 2026
@w1ndcn w1ndcn deleted the w1ndcn/fix/sphinx-conditional-exec branch June 10, 2026 03:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ipython Sphinx directive executes code when excluded by only, ifconfig

1 participant