Skip to content

Latest commit

 

History

History
71 lines (48 loc) · 2.59 KB

Jupyter_Notebooks_Apply_black_on_notebook_file.md

File metadata and controls

71 lines (48 loc) · 2.59 KB



Template request | Bug report | Generate Data Product

Tags: #jupyter #notebook #black #python #formatting #style

Author: Florent Ravenel

Description: This notebook explains how to apply the black formatting style to a Jupyter Notebook file. It is usefull for organizations that want to ensure a consistent coding style across their notebooks.

References:

Input

Import libraries

import json
import subprocess

Setup Variables

  • file_path: Path of the Jupyter Notebook file to be formatted
file_path = "<your_notebook_path.ipynb>"

Model

Apply black formatting

def run_black(file, file_output=None):
    # Open notebook
    with open(file) as f:
        nb = json.load(f)
    
    # Apply black on code cell
    for cell in nb['cells']:
        if cell['cell_type'] == 'code':
            code = cell['source']
            code = "".join(code)
            result = subprocess.run(['black', '-', '--fast'], input=code.encode(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.stdout:
                new_code = result.stdout.decode()
                if new_code.endswith("\n"):
                    new_code = new_code[:-1]
                cell['source'] = new_code
                
    # Save notebook
    if not file_output:
        file_output = file
    with open(file_output, 'w') as f:
        json.dump(nb, f, indent=1)
    print(f"✅ Black successfully applied to your notebook.")

Output

Run function

run_black(file_path)