Back to main.

Calmcode Shorts

nbqa logonbqa

Many of our favorite code checking tools in python (like, black and flake8) only work on .py files. That's a shame because it opens the door to bad code quality for all of our .ipynb notebook files. It turns out though that we're about to use nbqa for this use-case.

Install: nbqa, flake8 and black

You can install just nbqa but this won't install the checking tools that we'd like to use. To install all tools you'll need to run:

python -m pip install nbqa flake8 black

Run nbqa with black --check

To lint normal python files you could use black via:

black --check <pyfile>

To run it on notebooks, you can prepend it with nbqa.

nbqa black --check <ipynb file>

Run nbqa with flake8

This also works with flake8!

nbqa flake8 <ipynb file>

Run nbqa with black

If you'd like to use nbqa with a formatter (a tool that changes the file on your behalf) you can run it with the --nbqa-diff flag so that you can see a preview of the changes first.

nbqa black <ipynb file> --nbqa-diff

To change the file on disk, you can run:

nbqa black <ipynb file>

Note that you may want to close the notebook file and make sure it's no longer running in the background to see the changes. Otherwise Jupyter may accidentally override it again.

Run nbqa with pre-commit

You can configure nbqa to run on each commit by configuring the pre-commit hook. Your .pre-commit-config.yaml-file would contain a segment similar to:

- repo: https://github.com/nbQA-dev/nbQA
  rev: 1.1.1
  hooks:
    - id: nbqa-black
    - id: nbqa-flake8

If you're unfamiliar, please check our pre-commit course to learn how to it up first.

More options

Check the documentation of the project to learn more about:


Back to main.