docs/guides/using_black_with_jupyter_notebooks.md
Black supports formatting Jupyter Notebooks (.ipynb files) natively.
To format Jupyter Notebooks, install Black with the jupyter extra:
pip install "black[jupyter]"
Without the `jupyter` extra, _Black_ will not be able to format `.ipynb` files.
Once installed, you can format notebooks the same way you format Python files:
black notebook.ipynb
You can also format entire directories containing a mix of .py and .ipynb files:
black .
Black will automatically detect Jupyter Notebooks by their .ipynb extension and
format them accordingly.
If you're piping notebook content on standard input, use the --ipynb flag to tell
Black to treat the input as a Jupyter Notebook:
cat notebook.ipynb | black --ipynb -
Black formats the Python code cells in your notebook while preserving:
Only the source code within Python code cells is reformatted.
Black is cautious about formatting notebook cells. The following cells will not be formatted:
pip install black (without the % prefix)%%writefile script.py
print("hello")
%timeit f(1, \
2, \
3)
IPython's TransformerManager would
transform, e.g.:
get_ipython().system('ls')
If you notice a cell is not being formatted, it is likely because it contains one of the above constructs.
Additionally, Black cannot format Jupyter Notebooks with the --line-ranges option.
Black understands IPython magics, but is conservative about which cells it will format. By default, Black recognizes standard IPython magics.
If you use custom cell magics that contain Python code, you can tell Black about them
using the --python-cell-magics flag:
black --python-cell-magics writefile notebook.ipynb
This also works in pyproject.toml:
[tool.black]
python-cell-magics = ["writefile", "my_custom_magic"]
Simply replace the black hook with black-jupyter.
repos:
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 26.3.1
hooks:
- id: black-jupyter
language_version: python3.11
See the source version control integration docs for more examples of using Black with pre-commit.
Set the jupyter option to true.
- uses: psf/black@stable
with:
jupyter: true
See the GitHub Actions integration docs for more examples of using Black with GitHub Actions.