Skip to content

Commit

Permalink
Comment variables created from magic commands (#794)
Browse files Browse the repository at this point in the history
* New option --use-source-timestamp

* Write the output notebook just once
Adjust 'formats', if required, before writing the notebook

* Variables assigned from a magic command are commented out in `py` scripts
  • Loading branch information
mwouts authored May 30, 2021
1 parent 112ed80 commit ba932cd
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 2 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ Jupytext ChangeLog

**Fixed**
- Dependencies of the JupyterLab extension have been upgraded to fix a security vulnerability ([#783](https://github.com/mwouts/jupytext/issues/783))
- Variables assigned from a magic command are commented out in `py` scripts ([#781](https://github.com/mwouts/jupytext/issues/781))


1.11.2 (2021-05-02)
-------------------
Expand Down
6 changes: 6 additions & 0 deletions jupytext/magics.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@
# Python help commands end with ?
_IPYTHON_MAGIC_HELP = re.compile(r"^\s*(# )*[^\s]*\?\s*$")

_PYTHON_MAGIC_ASSIGN = re.compile(
r"^(# |#)*\s*([a-zA-Z_][a-zA-Z_$0-9]*)\s*=\s*(%|%%|%%%)[a-zA-Z](.*)"
)

_SCRIPT_LANGUAGES = [_SCRIPT_EXTENSIONS[ext]["language"] for ext in _SCRIPT_EXTENSIONS]


Expand All @@ -76,6 +80,8 @@ def is_magic(line, language, global_escape_flag=True, explicitly_code=False):
return False
if _PYTHON_HELP_OR_BASH_CMD.match(line):
return True
if _PYTHON_MAGIC_ASSIGN.match(line):
return True
if explicitly_code and _IPYTHON_MAGIC_HELP.match(line):
return True
return _PYTHON_MAGIC_CMD.match(line)
Expand Down
16 changes: 15 additions & 1 deletion tests/test_escape_magics.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@

import jupytext
from jupytext.compare import compare, compare_notebooks
from jupytext.magics import comment_magic, is_magic, uncomment_magic, unesc
from jupytext.magics import (
_PYTHON_MAGIC_ASSIGN,
comment_magic,
is_magic,
uncomment_magic,
unesc,
)

from .utils import notebook_model

Expand Down Expand Up @@ -276,3 +282,11 @@ def test_indented_magic():
assert uncomment_magic([" # !rm file"]) == [" !rm file"]
assert comment_magic([" %cd"]) == [" # %cd"]
assert uncomment_magic([" # %cd"]) == [" %cd"]


def test_magic_assign_781():
assert _PYTHON_MAGIC_ASSIGN.match("name = %magic")
assert _PYTHON_MAGIC_ASSIGN.match("# name = %magic")
assert not _PYTHON_MAGIC_ASSIGN.match("# not a name = %magic")
assert not _PYTHON_MAGIC_ASSIGN.match("# 0name = %magic")
assert is_magic("result = %sql SELECT * FROM quickdemo WHERE value > 25", "python")

0 comments on commit ba932cd

Please sign in to comment.