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

Function mask_cell

src/black/handle_ipynb_magics.py:148–187  ·  view source on GitHub ↗

Mask IPython magics so content becomes parseable Python code. For example, %matplotlib inline 'foo' becomes b"25716f358c32750" 'foo' The replacements are returned, along with the transformed code.

(src: str)

Source from the content-addressed store, hash-verified

146
147
148def mask_cell(src: str) -> tuple[str, list[Replacement]]:
149 """Mask IPython magics so content becomes parseable Python code.
150
151 For example,
152
153 %matplotlib inline
154 'foo'
155
156 becomes
157
158 b"25716f358c32750"
159 'foo'
160
161 The replacements are returned, along with the transformed code.
162 """
163 replacements: list[Replacement] = []
164 try:
165 ast.parse(src)
166 except SyntaxError:
167 # Might have IPython magics, will process below.
168 pass
169 else:
170 # Syntax is fine, nothing to mask, early return.
171 return src, replacements
172
173 from IPython.core.inputtransformer2 import TransformerManager
174
175 transformer_manager = TransformerManager()
176 # A side effect of the following transformation is that it also removes any
177 # empty lines at the beginning of the cell.
178 transformed = transformer_manager.transform_cell(src)
179 transformed, cell_magic_replacements = replace_cell_magics(transformed)
180 replacements += cell_magic_replacements
181 transformed = transformer_manager.transform_cell(transformed)
182 transformed, magic_replacements = replace_magics(transformed)
183 if len(transformed.strip().splitlines()) != len(src.strip().splitlines()):
184 # Multi-line magic, not supported.
185 raise NothingChanged
186 replacements += magic_replacements
187 return transformed, replacements
188
189
190def create_token(n_chars: int) -> str:

Callers 1

format_cellFunction · 0.90

Calls 3

replace_cell_magicsFunction · 0.85
replace_magicsFunction · 0.85
parseMethod · 0.45

Tested by

no test coverage detected