diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index eb8011c7a..62a8b6051 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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) ------------------- diff --git a/jupytext/magics.py b/jupytext/magics.py index b8c0173d1..be0e5381b 100644 --- a/jupytext/magics.py +++ b/jupytext/magics.py @@ -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] @@ -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) diff --git a/tests/test_escape_magics.py b/tests/test_escape_magics.py index 8507adc5f..f72627cba 100644 --- a/tests/test_escape_magics.py +++ b/tests/test_escape_magics.py @@ -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 @@ -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")