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:
import json
import subprocess
file_path
: Path of the Jupyter Notebook file to be formatted
file_path = "<your_notebook_path.ipynb>"
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.")
run_black(file_path)