Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
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
17 changes: 17 additions & 0 deletions 17 IPython/core/inputtransformer2.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,22 @@ def leading_empty_lines(lines):
return lines


def leading_comment_lines(lines):
"""Remove leading comments before a cell magic.

Cell magics must be the first meaningful line in a cell. Comments and
blank lines preceding a cell magic do not affect its execution, so remove
them before detecting the magic.
"""
for i, line in enumerate(lines):
if not line.strip() or line.lstrip().startswith("#"):
continue
if line.startswith("%%"):
return lines[i:]
break
return lines


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

Expand Down Expand Up @@ -708,6 +724,7 @@ def __init__(self):
leading_indent,
classic_prompt,
ipython_prompt,
leading_comment_lines,
]
self.line_transforms = [
cell_magic,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Leading comments before cell magics
===================================

Leading comments and blank lines are ignored before a cell magic, so a cell
such as ``# setup`` followed by ``%%time`` is treated as a cell magic instead
of an invalid line magic.
16 changes: 16 additions & 0 deletions 16 tests/test_inputtransformer2_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,22 @@ def test_cell_magic():
assert ipt2.cell_magic(sample.splitlines(keepends=True)) == expected.splitlines(keepends=True)


def test_leading_comments_before_cell_magic():
cell = "# Set up timing\n\n# Measure this expression\n%%time\npass\n"

assert ipt2.TransformerManager().transform_cell(cell) == (
"get_ipython().run_cell_magic('time', '', 'pass\\n')\n"
)


def test_leading_prompted_comments_before_cell_magic():
cell = "In [1]: # Set up timing\n ...: %%time\n ...: pass\n"

assert ipt2.TransformerManager().transform_cell(cell) == (
"get_ipython().run_cell_magic('time', '', 'pass\\n')\n"
)


CLASSIC_PROMPT = (
"""\
>>> for a in range(5):
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.