def preprocess_cell(self, cell: NotebookNode, resources, index): if cell.cell_type == 'code': for match in re.finditer(r'^%{1,2}(?P<magic>[^ \n\t]*) (?P<parameters>.*)$', cell.source): magic = match.group('magic') parameters = match.group('parameters').split() resources['magics'][magic] = parameters cell.source = cell.source[:match.start()] + cell.source[match.end() + 1:] return cell, resources
def blacken_code(cell: NotebookNode, resources: dict, index: int) -> Tuple[NotebookNode, dict]: """Format python source code with black (see https://black.readthedocs.io).""" try: import black except ImportError: raise ImportError( "black not installed: see https://black.readthedocs.io") if cell.get("cell_type", None) != "code": return cell, resources # TODO use metadata to set target versions and whether to raise on exceptions # i.e. black.FileMode(target_versions, {black.TargetVersion.PY36}) try: cell.source = black.format_str(cell.source, mode=black.FileMode()) except (SyntaxError, black.InvalidInput): logger.debug(f"cell {index} could not be formatted by black.") # code cells don't require a trailing new line cell.source = cell.source.rstrip() return cell, resources