Using Black with Jupyter Notebooks¶
Black supports formatting Jupyter Notebooks (.ipynb files) natively.
Installation¶
To format Jupyter Notebooks, install Black with the jupyter extra:
pip install "black[jupyter]"
Note
Without the jupyter extra, Black will not be able to format .ipynb files.
Basic usage¶
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.
Formatting via standard input¶
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 -
What is (and isn’t) formatted¶
Black formats the Python code cells in your notebook while preserving:
Markdown cells
Cell outputs
Cell metadata
Notebook metadata
Only the source code within Python code cells is reformatted.
Cells that Black will skip¶
Black is cautious about formatting notebook cells. The following cells will not be formatted:
Automagics — e.g.
pip install black(without the%prefix)Non-Python cell magics — e.g.:
%%writefile script.py print("hello")
Multiline magics — e.g.:
%timeit f(1, \ 2, \ 3)
IPython internal calls — code that
IPython’sTransformerManagerwould transform, e.g.:get_ipython().system('ls')
Invalid syntax — as it cannot be safely distinguished from automagics without a running IPython kernel.
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.
Cell magics¶
Black understands IPython magics, but is conservative about which cells it will format. By default, Black recognizes standard IPython magics.
Custom python cell 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"]
Integrations¶
pre-commit¶
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.
GitHub Actions¶
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.