MCPcopy
hub / github.com/psf/black / format_cell

Function format_cell

src/black/__init__.py:1130–1164  ·  view source on GitHub ↗

Format code in given cell of Jupyter notebook. General idea is: - if cell has trailing semicolon, remove it; - if cell has IPython magics, mask them; - format cell; - reinstate IPython magics; - reinstate trailing semicolon (if originally present); - strip t

(src: str, *, fast: bool, mode: Mode)

Source from the content-addressed store, hash-verified

1128
1129
1130def format_cell(src: str, *, fast: bool, mode: Mode) -> str:
1131 """Format code in given cell of Jupyter notebook.
1132
1133 General idea is:
1134
1135 - if cell has trailing semicolon, remove it;
1136 - if cell has IPython magics, mask them;
1137 - format cell;
1138 - reinstate IPython magics;
1139 - reinstate trailing semicolon (if originally present);
1140 - strip trailing newlines.
1141
1142 Cells with syntax errors will not be processed, as they
1143 could potentially be automagics or multi-line magics, which
1144 are currently not supported.
1145 """
1146 validate_cell(src, mode)
1147 src_without_trailing_semicolon, has_trailing_semicolon = remove_trailing_semicolon(
1148 src
1149 )
1150 try:
1151 masked_src, replacements = mask_cell(src_without_trailing_semicolon)
1152 except SyntaxError:
1153 raise NothingChanged from None
1154 masked_dst = format_str(masked_src, mode=mode)
1155 if not fast:
1156 check_stability_and_equivalence(masked_src, masked_dst, mode=mode)
1157 dst_without_trailing_semicolon = unmask_cell(masked_dst, replacements)
1158 dst = put_trailing_semicolon_back(
1159 dst_without_trailing_semicolon, has_trailing_semicolon
1160 )
1161 dst = dst.rstrip("\n")
1162 if dst == src:
1163 raise NothingChanged from None
1164 return dst
1165
1166
1167def validate_metadata(nb: MutableMapping[str, Any]) -> None:

Callers 15

test_noopFunction · 0.90
test_trailing_semicolonFunction · 0.90
test_cell_magicFunction · 0.90
test_cell_magic_noopFunction · 0.90
test_magicFunction · 0.90
test_non_python_magicsFunction · 0.90
test_set_inputFunction · 0.90

Calls 7

validate_cellFunction · 0.90
mask_cellFunction · 0.90
unmask_cellFunction · 0.90
format_strFunction · 0.85

Tested by 15

test_noopFunction · 0.72
test_trailing_semicolonFunction · 0.72
test_cell_magicFunction · 0.72
test_cell_magic_noopFunction · 0.72
test_magicFunction · 0.72
test_non_python_magicsFunction · 0.72
test_set_inputFunction · 0.72