Skip to content

Commit

Permalink
Handle comments in multi-line cell outputs (#6736)
Browse files Browse the repository at this point in the history
  • Loading branch information
philippjfr authored Apr 16, 2024
1 parent 4b9f139 commit 47d9ebb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
4 changes: 3 additions & 1 deletion panel/io/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ def capture_code_cell(cell):
parses = False
while not parses:
try:
if not cell_out.strip():
raise SyntaxError
ast.parse(cell_out)
parses = True
except SyntaxError:
Expand All @@ -185,7 +187,7 @@ def capture_code_cell(cell):
return code

# Remove code comments
if '#' in cell_out:
if '#' in cell_out and not cell_out.count('\n'):
try:
# To not remove "#000000"
cell_tmp = cell_out[:cell_out.index('#')].rstrip()
Expand Down
31 changes: 31 additions & 0 deletions panel/tests/io/test_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@
'test.csv'
)"""

code_function = """
def foo():
# Comment
return 1+1
"""

code_expr_multi_line_with_comment = """
(
1 + 1 # Comment
)
"""

def test_extract_panel_block():
f = StringIO(md1)
Expand Down Expand Up @@ -110,6 +121,26 @@ def test_capture_code_cell_expression():
_pn__state._cell_outputs['foo'].append(_fig__out)
"""]

def test_capture_code_cell_function():
assert capture_code_cell({'id': 'foo', 'source': code_function}) == [
'', 'def foo():\n # Comment\n return 1+1\n'
]

def test_capture_code_expression_multi_line_with_comment():
assert capture_code_cell({'id': 'foo', 'source': code_expr_multi_line_with_comment}) == [
'', """\
_pn__state._cell_outputs['foo'].append(((
1 + 1 # Comment
)
))
for _cell__out in _CELL__DISPLAY:
_pn__state._cell_outputs['foo'].append(_cell__out)
_CELL__DISPLAY.clear()
_fig__out = _get__figure()
if _fig__out:
_pn__state._cell_outputs['foo'].append(_fig__out)
"""]


def test_capture_code_cell_multi_line_expression():
assert capture_code_cell({'id': 'foo', 'source': code_multi_line}) == [
Expand Down

0 comments on commit 47d9ebb

Please sign in to comment.