Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Recognise cell magics after leading comments. 🤖🤖
A narration comment above %%magic previously made the cell parse as a
line magic named %name. Drop those leading comments so the cell magic
runs, matching the existing leading-empty-line cleanup.

Fixes #15312
  • Loading branch information
00200200 committed Sep 29, 2026
commit d8d87b20ee89f51dc8db5b0964d2beea9378f724
28 changes: 28 additions & 0 deletions IPython/core/inputtransformer2.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,33 @@ def leading_empty_lines(lines):
return lines


def leading_comment_lines(lines):
"""Drop leading comments when the first code line is a cell magic.

Cell magics are only recognised on the first line of a cell. A narration
comment (or blank line) above ``%%magic`` used to make the magic parse as a
line magic named ``%name``, which then failed with a confusing error.

If the first non-empty, non-comment line starts with ``%%``, those leading
comments and blanks are stripped so the cell magic is recognised. Other
cells are left unchanged.
"""
if not lines:
return lines
first_code = None
for i, line in enumerate(lines):
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
first_code = i
break
if first_code is None:
return lines
if lines[first_code].startswith("%%"):
return lines[first_code:]
return lines


def leading_indent(lines):
"""Remove leading indentation.

Expand Down Expand Up @@ -708,6 +735,7 @@ def __init__(self):
leading_indent,
classic_prompt,
ipython_prompt,
leading_comment_lines,
]
self.line_transforms = [
cell_magic,
Expand Down
10 changes: 10 additions & 0 deletions docs/source/whatsnew/pr/cell-magic-leading-comments.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Cell magics after leading comments
==================================

A comment (or blank line) above a cell magic is now ignored, so a cell like::

# setup
%%time
pass

runs the cell magic instead of failing with a "line magic not found" error.
3 changes: 3 additions & 0 deletions tests/test_inputtransformer2.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,9 @@ def __init__(self, s):
pytest.param("def a():\n x=1\n global x", "invalid", None),
pytest.param("a \\ ", "invalid", None), # Nothing allowed after backslash,
pytest.param("1\\\n+2", "complete", None),
# Leading comments before a cell magic should be ignored for completeness
pytest.param("# setup\n%%foo\n", "incomplete", 0),
pytest.param("# setup\n%%foo\n\n", "complete", None),
]


Expand Down
96 changes: 96 additions & 0 deletions tests/test_inputtransformer2_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,102 @@ def test_leading_empty_lines(sample, expected):
assert ipt2.leading_empty_lines(sample.splitlines(keepends=True)) == expected.splitlines(keepends=True)


COMMENT_THEN_CELL_MAGIC = (
"""\
# setup
%%foo arg
body
""",
"""\
%%foo arg
body
""",
)

COMMENTS_BLANKS_THEN_CELL_MAGIC = (
"""\
# setup

# more
%%foo
body
""",
"""\
%%foo
body
""",
)

COMMENT_THEN_PYTHON = (
"""\
# setup
x = 1
""",
"""\
# setup
x = 1
""",
)

COMMENT_THEN_LINE_MAGIC = (
"""\
# setup
%foo
""",
"""\
# setup
%foo
""",
)

ONLY_COMMENTS = (
"""\
# only
# comments
""",
"""\
# only
# comments
""",
)

CELL_MAGIC_ALREADY_FIRST = (
"""\
%%foo arg
body 1
body 2
""",
"""\
%%foo arg
body 1
body 2
""",
)


@pytest.mark.parametrize(
"sample,expected",
[
COMMENT_THEN_CELL_MAGIC,
COMMENTS_BLANKS_THEN_CELL_MAGIC,
COMMENT_THEN_PYTHON,
COMMENT_THEN_LINE_MAGIC,
ONLY_COMMENTS,
CELL_MAGIC_ALREADY_FIRST,
],
)
def test_leading_comment_lines(sample, expected):
assert ipt2.leading_comment_lines(
sample.splitlines(keepends=True)
) == expected.splitlines(keepends=True)


def test_transform_cell_comment_before_cell_magic():
mgr = ipt2.TransformerManager()
out = mgr.transform_cell("# setup\n%%foo arg\nbody 1\nbody 2\n")
assert out == "get_ipython().run_cell_magic('foo', 'arg', 'body 1\\nbody 2\\n')\n"


CRLF_MAGIC = (["%%ls\r\n"], ["get_ipython().run_cell_magic('ls', '', '')\n"])


Expand Down
16 changes: 16 additions & 0 deletions tests/test_magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1244,6 +1244,22 @@ def cellm(line, cell):
check_ident("cellm")


def test_cell_magic_after_leading_comment(underscore_not_in_builtins):
"""Leading comments must not turn a cell magic into a line magic named %name."""

@register_cell_magic
def cellm_comment(line, cell):
return line, cell

result = _ip.run_cell("# setup\n%%cellm_comment a\nb\n")
assert result.success
assert _ip.user_ns["_"] == ("a", "b\n")

result = _ip.run_cell("# setup\n\n# more\n%%cellm_comment c\nd\n")
assert result.success
assert _ip.user_ns["_"] == ("c", "d\n")


def test_cell_magic_reg(underscore_not_in_builtins):
"Cell magic manually registered"

Expand Down
Loading