Skip to content

Commit cf5f549

Browse files
authored
Replace magics with comments only when in Jupyter notebooks. (#847)
1 parent e8feeb1 commit cf5f549

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

scalene/scalene_analysis.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import ast
22
import importlib
33
import os
4+
import re
45
import sys
56

67
from typing import cast, Any, Dict, List, Tuple
@@ -207,9 +208,13 @@ def walk(
207208

208209
@staticmethod
209210
def strip_magic_line(source: str) -> str:
210-
# Filter out any magic lines (starting with %) if in a Jupyter notebook
211-
import re
211+
try:
212+
from IPython import get_ipython
213+
get_ipython()
214+
# The above line will fail if not running in a notebook,
215+
# in which case we return the original source unchanged.
216+
# Regular expression to match and replace magic commands with comments
217+
source = re.sub(r'(^\s*)%{1,2}', r'\1#', source, flags=re.MULTILINE)
218+
finally:
219+
return source
212220

213-
srclines = map(lambda x: re.sub(r"^\%.*", "", x), source.split("\n"))
214-
source = "\n".join(srclines)
215-
return source

0 commit comments

Comments
 (0)