All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
1 """Functions to process IPython magics with."""
8 from functools import lru_cache
9 from typing import Dict, List, Optional, Tuple
11 if sys.version_info >= (3, 10):
12 from typing import TypeGuard
14 from typing_extensions import TypeGuard
16 from black.output import out
17 from black.report import NothingChanged
19 TRANSFORMED_MAGICS = frozenset(
21 "get_ipython().run_cell_magic",
22 "get_ipython().system",
23 "get_ipython().getoutput",
24 "get_ipython().run_line_magic",
27 TOKENS_TO_IGNORE = frozenset(
38 PYTHON_CELL_MAGICS = frozenset(
49 TOKEN_HEX = secrets.token_hex
52 @dataclasses.dataclass(frozen=True)
59 def jupyter_dependencies_are_installed(*, verbose: bool, quiet: bool) -> bool:
61 import IPython # noqa:F401
62 import tokenize_rt # noqa:F401
63 except ModuleNotFoundError:
64 if verbose or not quiet:
66 "Skipping .ipynb files as Jupyter dependencies are not installed.\n"
67 'You can fix this by running ``pip install "black[jupyter]"``'
75 def remove_trailing_semicolon(src: str) -> Tuple[str, bool]:
76 """Remove trailing semicolon from Jupyter notebook cell.
80 fig, ax = plt.subplots()
81 ax.plot(x_data, y_data); # plot data
85 fig, ax = plt.subplots()
86 ax.plot(x_data, y_data) # plot data
88 Mirrors the logic in `quiet` from `IPython.core.displayhook`, but uses
89 ``tokenize_rt`` so that round-tripping works fine.
91 from tokenize_rt import reversed_enumerate, src_to_tokens, tokens_to_src
93 tokens = src_to_tokens(src)
94 trailing_semicolon = False
95 for idx, token in reversed_enumerate(tokens):
96 if token.name in TOKENS_TO_IGNORE:
98 if token.name == "OP" and token.src == ";":
100 trailing_semicolon = True
102 if not trailing_semicolon:
104 return tokens_to_src(tokens), True
107 def put_trailing_semicolon_back(src: str, has_trailing_semicolon: bool) -> str:
108 """Put trailing semicolon back if cell originally had it.
110 Mirrors the logic in `quiet` from `IPython.core.displayhook`, but uses
111 ``tokenize_rt`` so that round-tripping works fine.
113 if not has_trailing_semicolon:
115 from tokenize_rt import reversed_enumerate, src_to_tokens, tokens_to_src
117 tokens = src_to_tokens(src)
118 for idx, token in reversed_enumerate(tokens):
119 if token.name in TOKENS_TO_IGNORE:
121 tokens[idx] = token._replace(src=token.src + ";")
123 else: # pragma: nocover
124 raise AssertionError(
125 "INTERNAL ERROR: Was not able to reinstate trailing semicolon. "
126 "Please report a bug on https://github.com/psf/black/issues. "
128 return str(tokens_to_src(tokens))
131 def mask_cell(src: str) -> Tuple[str, List[Replacement]]:
132 """Mask IPython magics so content becomes parseable Python code.
144 The replacements are returned, along with the transformed code.
146 replacements: List[Replacement] = []
150 # Might have IPython magics, will process below.
153 # Syntax is fine, nothing to mask, early return.
154 return src, replacements
156 from IPython.core.inputtransformer2 import TransformerManager
158 transformer_manager = TransformerManager()
159 transformed = transformer_manager.transform_cell(src)
160 transformed, cell_magic_replacements = replace_cell_magics(transformed)
161 replacements += cell_magic_replacements
162 transformed = transformer_manager.transform_cell(transformed)
163 transformed, magic_replacements = replace_magics(transformed)
164 if len(transformed.splitlines()) != len(src.splitlines()):
165 # Multi-line magic, not supported.
167 replacements += magic_replacements
168 return transformed, replacements
171 def get_token(src: str, magic: str) -> str:
172 """Return randomly generated token to mask IPython magic with.
174 For example, if 'magic' was `%matplotlib inline`, then a possible
175 token to mask it with would be `"43fdd17f7e5ddc83"`. The token
176 will be the same length as the magic, and we make sure that it was
177 not already present anywhere else in the cell.
180 nbytes = max(len(magic) // 2 - 1, 1)
181 token = TOKEN_HEX(nbytes)
184 token = TOKEN_HEX(nbytes)
187 raise AssertionError(
188 "INTERNAL ERROR: Black was not able to replace IPython magic. "
189 "Please report a bug on https://github.com/psf/black/issues. "
190 f"The magic might be helpful: {magic}"
192 if len(token) + 2 < len(magic):
197 def replace_cell_magics(src: str) -> Tuple[str, List[Replacement]]:
198 """Replace cell magic with token.
200 Note that 'src' will already have been processed by IPython's
201 TransformerManager().transform_cell.
205 get_ipython().run_cell_magic('t', '-n1', 'ls =!ls\\n')
212 The replacement, along with the transformed code, is returned.
214 replacements: List[Replacement] = []
216 tree = ast.parse(src)
218 cell_magic_finder = CellMagicFinder()
219 cell_magic_finder.visit(tree)
220 if cell_magic_finder.cell_magic is None:
221 return src, replacements
222 header = cell_magic_finder.cell_magic.header
223 mask = get_token(src, header)
224 replacements.append(Replacement(mask=mask, src=header))
225 return f"{mask}\n{cell_magic_finder.cell_magic.body}", replacements
228 def replace_magics(src: str) -> Tuple[str, List[Replacement]]:
229 """Replace magics within body of cell.
231 Note that 'src' will already have been processed by IPython's
232 TransformerManager().transform_cell.
236 get_ipython().run_line_magic('matplotlib', 'inline')
244 The replacement, along with the transformed code, are returned.
247 magic_finder = MagicFinder()
248 magic_finder.visit(ast.parse(src))
250 for i, line in enumerate(src.splitlines(), start=1):
251 if i in magic_finder.magics:
252 offsets_and_magics = magic_finder.magics[i]
253 if len(offsets_and_magics) != 1: # pragma: nocover
254 raise AssertionError(
255 f"Expecting one magic per line, got: {offsets_and_magics}\n"
256 "Please report a bug on https://github.com/psf/black/issues."
258 col_offset, magic = (
259 offsets_and_magics[0].col_offset,
260 offsets_and_magics[0].magic,
262 mask = get_token(src, magic)
263 replacements.append(Replacement(mask=mask, src=magic))
264 line = line[:col_offset] + mask
265 new_srcs.append(line)
266 return "\n".join(new_srcs), replacements
269 def unmask_cell(src: str, replacements: List[Replacement]) -> str:
270 """Remove replacements from cell.
282 for replacement in replacements:
283 src = src.replace(replacement.mask, replacement.src)
287 def _is_ipython_magic(node: ast.expr) -> TypeGuard[ast.Attribute]:
288 """Check if attribute is IPython magic.
290 Note that the source of the abstract syntax tree
291 will already have been processed by IPython's
292 TransformerManager().transform_cell.
295 isinstance(node, ast.Attribute)
296 and isinstance(node.value, ast.Call)
297 and isinstance(node.value.func, ast.Name)
298 and node.value.func.id == "get_ipython"
302 def _get_str_args(args: List[ast.expr]) -> List[str]:
305 assert isinstance(arg, ast.Str)
306 str_args.append(arg.s)
310 @dataclasses.dataclass(frozen=True)
313 params: Optional[str]
317 def header(self) -> str:
319 return f"%%{self.name} {self.params}"
320 return f"%%{self.name}"
323 # ast.NodeVisitor + dataclass = breakage under mypyc.
324 class CellMagicFinder(ast.NodeVisitor):
327 Note that the source of the abstract syntax tree
328 will already have been processed by IPython's
329 TransformerManager().transform_cell.
335 would have been transformed to
337 get_ipython().run_cell_magic('time', '', 'foo()\\n')
339 and we look for instances of the latter.
342 def __init__(self, cell_magic: Optional[CellMagic] = None) -> None:
343 self.cell_magic = cell_magic
345 def visit_Expr(self, node: ast.Expr) -> None:
346 """Find cell magic, extract header and body."""
348 isinstance(node.value, ast.Call)
349 and _is_ipython_magic(node.value.func)
350 and node.value.func.attr == "run_cell_magic"
352 args = _get_str_args(node.value.args)
353 self.cell_magic = CellMagic(name=args[0], params=args[1], body=args[2])
354 self.generic_visit(node)
357 @dataclasses.dataclass(frozen=True)
358 class OffsetAndMagic:
363 # Unsurprisingly, subclassing ast.NodeVisitor means we can't use dataclasses here
364 # as mypyc will generate broken code.
365 class MagicFinder(ast.NodeVisitor):
366 """Visit cell to look for get_ipython calls.
368 Note that the source of the abstract syntax tree
369 will already have been processed by IPython's
370 TransformerManager().transform_cell.
376 would have been transformed to
378 get_ipython().run_line_magic('matplotlib', 'inline')
380 and we look for instances of the latter (and likewise for other
384 def __init__(self) -> None:
385 self.magics: Dict[int, List[OffsetAndMagic]] = collections.defaultdict(list)
387 def visit_Assign(self, node: ast.Assign) -> None:
388 """Look for system assign magics.
392 black_version = !black --version
395 would have been (respectively) transformed to
397 black_version = get_ipython().getoutput('black --version')
398 env = get_ipython().run_line_magic('env', 'var')
400 and we look for instances of any of the latter.
402 if isinstance(node.value, ast.Call) and _is_ipython_magic(node.value.func):
403 args = _get_str_args(node.value.args)
404 if node.value.func.attr == "getoutput":
406 elif node.value.func.attr == "run_line_magic":
411 raise AssertionError(
412 f"Unexpected IPython magic {node.value.func.attr!r} found. "
413 "Please report a bug on https://github.com/psf/black/issues."
415 self.magics[node.value.lineno].append(
416 OffsetAndMagic(node.value.col_offset, src)
418 self.generic_visit(node)
420 def visit_Expr(self, node: ast.Expr) -> None:
421 """Look for magics in body of cell.
430 would (respectively) get transformed to
432 get_ipython().system('ls')
433 get_ipython().getoutput('ls')
434 get_ipython().run_line_magic('pinfo', 'ls')
435 get_ipython().run_line_magic('pinfo2', 'ls')
437 and we look for instances of any of the latter.
439 if isinstance(node.value, ast.Call) and _is_ipython_magic(node.value.func):
440 args = _get_str_args(node.value.args)
441 if node.value.func.attr == "run_line_magic":
442 if args[0] == "pinfo":
444 elif args[0] == "pinfo2":
450 elif node.value.func.attr == "system":
452 elif node.value.func.attr == "getoutput":
455 raise NothingChanged # unsupported magic.
456 self.magics[node.value.lineno].append(
457 OffsetAndMagic(node.value.col_offset, src)
459 self.generic_visit(node)