Run isort, pyupgrade, mypy, pylint, flake8, and more on Jupyter Notebooks

Overview

nbQA

Run isort, pyupgrade, mypy, pylint, flake8, mdformat, black, blacken-docs, and more on Jupyter Notebooks

tox codecov pre-commit

versions chat docs

downloads

demo

  • handles IPython magics robustly
  • respects your config files
  • preserves "quiet mode" trailing semicolons
  • lints both code and markdown cells

Table of contents

🎉 Installation

In your virtual environment, run (note: the $ is not part of the command):

$ python -m pip install -U nbqa

Or, if you are using conda:

$ conda install -c conda-forge nbqa

🚀 Examples

Command-line

Reformat your notebooks with black:

$ nbqa black my_notebook.ipynb
reformatted my_notebook.ipynb
All done! ✨ 🍰 ✨
1 files reformatted.

Sort your imports with isort:

$ nbqa isort my_notebook.ipynb
Fixing my_notebook.ipynb

Upgrade your syntax with pyupgrade:

$ nbqa pyupgrade my_notebook.ipynb --py36-plus
Rewriting my_notebook.ipynb

Format your markdown cells with mdformat:

$ nbqa mdformat my_notebook.ipynb --nbqa-md --nbqa-diff
Cell 2
------
--- my_notebook.ipynb
+++ my_notebook.ipynb
@@ -1,2 +1 @@
-First level heading
-===
+# First level heading

To apply these changes, remove the `--nbqa-diff` flag

See command-line examples for examples involving doctest, flake8, mypy, pylint, autopep8, pydocstyle, and yapf.

Pre-commit

Here's an example of how to set up some pre-commit hooks: put this in your .pre-commit-config.yaml file (see usage as pre-commit hook)

- repo: https://github.com/nbQA-dev/nbQA
  rev: 1.2.2
  hooks:
    - id: nbqa-black
    - id: nbqa-pyupgrade
      args: [--py36-plus]
    - id: nbqa-isort

If you need to select specific versions of any of these linters/formatters, add them to additional_dependencies.

🥳 Used by

Click here for (non-exhaustive) list of repos

Is your project missing? Let us know, or open a pull request!

💬 Testimonials

Michael Kennedy & Brian Okken, hosts of the Python Bytes podcast:

This is really cool. I think it brings so much of the code formatting and code analysis, clean up to notebooks, which I think had been really lacking

Nikita Sobolev, CTO at wemake.services:

It is amazing!

Alex Andorra, Data Scientist, ArviZ & PyMC Dev, Host of 'Learning Bayesian Statistics' Podcast:

well done on nbqa @MarcoGorelli ! Will be super useful in CI

Matthew Feickert, Postdoc at University of Illinois working on LHC physics:

nbqa in your pre-commit hooks along with @codewithanthony 's pre-commit CI service is amazing! Everyone using Jupyter notebooks should be doing this.

Girish Pasupathy, Software engineer and now core-contributor:

thanks a lot for your effort to create such a useful tool

Simon Brugman, Data scientist & pandas-profiling dev:

nbQA helps us to keep notebooks to the same standards as the rest of the code. If you're serious about your code standards, you should keep them consistent across both notebooks and python scripts. Great addition to the ecosystem, thanks!

Bradley Dice, PhD Candidate in Physics & Scientific Computing:

nbqa is a clean, easy to use, and effective tool for notebook code style. Formatting and readability makes a huge difference when rendering notebooks in a project's documentation!

James Lamb, engineer @saturn_cloud, LightGBM maintainer

today I learned about nbqa, a command-line tool to run linters like flake8 over #Python code in @ProjectJupyter notebooks. Thanks to @jayyqi for pointing me to it. So far, I really really like it.

Lars Yencken, Tech Lead @ Our World In Data

Super useful! I only wish it was built-in to Jupyterlab.

Vincent D. Warmerdam, maintainer @ calmcode.io

Nice. nbQA looks like a great way to prevent the Untitled12.ipynb-phenomenon. I like!

👥 Contributing

I will give write-access to anyone who makes a useful pull request - see the contributing guide for details on how to do so.

Thanks goes to these wonderful people (emoji key):


Marco Gorelli

💻 🚧 👀 ⚠️ 🤔

Sebastian Weigand

🔧 👀 📖 🤔

Girish Pasupathy

💻 🚇 🐛 👀 🤔

fcatus

🚇

HD23me

🐛

mani

🤔 🚇

Daniel Mietchen

🤔

Michał Gacka

🐛

Happy

📖

Nat Taylor

🤔 💻 🔧 🐛

Caio Ariede

📖

Nikita Sobolev

🤔 🐛 📖

Amichay Oren

🤔

pylang

🤔

Henry Schreiner

🐛

Kaiqi Dong

📖

Simon Brugman

🐛

John Sandall

🐛

Nathan Cooper

🐛

agruenberger

🐛

Rafal Wojdyla

🐛

Bradley Dice

🤔 💻

Ivan Cheung

🐛

Tony Hirst

🐛

Taneli Hukkinen

🚧

Tom Begley

🤔 💻 📖

Steven DeMartini

📖

vincent d warmerdam


Daniel Sparing

🐛

asdfCYBER

📖

This project follows the all-contributors specification. Contributions of any kind welcome!

Comments
  • Handle python code present as part of line magics

    Handle python code present as part of line magics

    Takes care of issue #279 and also helps to support autoflake #313 .

    • [ ] Test current changes on external notebooks

    This PR is ready for review. But before merging I would like to run on some external notebooks.

    opened by girip11 36
  • Can autoreload magics be kept above isort output?

    Can autoreload magics be kept above isort output?

    I have tried to look around, but I am not sure if one of the recent fixed addresses this problem. I am using nbQA for its isort functionality and have the following problem.

    A notebook which looks like this (MWE)

    %load_ext autoreload
    %autoreload 2
    
    import sys
    import pathlib
    

    is converted by nbqa isort into

    import pathlib
    import sys
    
    %load_ext autoreload
    %autoreload 2
    

    which actually invalidates the autoreload extension that must be loaded before any imports. I have tried to use # isort:skip or put it in a different cell, but to no avail. Do you know if there's a fix for this?

    Otherwise, thanks for the great hooks!

    needs info 
    opened by Alexander-Serov 33
  • Proper way to use nbqa-mypy

    Proper way to use nbqa-mypy

    Thanks for your work! I have a question, that might convert into an issue, so I'm trying to use nbqa-mypy, my config looks like this:

      - repo: https://github.com/nbQA-dev/nbQA
        rev: 0.5.7
        hooks:
          - id: nbqa-mypy
            args: ["--nbqa-ignore-cells=%%R", "--strict", "--show-error-codes"]
    

    But I'm getting error about missing modules that are part of the repository, example:

    pipelines/notebooks/foo.ipynb:cell_2:1: error: Cannot find implementation or library stub for module named 'my_utils'  [import
    

    Where the repo contains {pipelines, my_utils} in the root, and import from my_utils doesn't raise issues in py modules and vanilla mypy checks. Am I doing sth wrong? Is there a blessed way to use nbqa-mypy and give access to the main repo? Maybe nbqa-mypy is missing some step to add repo to the pre-commit's nbqa-mypy virtualenv?

    bug 
    opened by ravwojdyla 28
  • Added pylint as a pre-commit hook.

    Added pylint as a pre-commit hook.

    closes #203

    Removed separate github actions for running pylint.

    Changes to be committed: deleted: .github/workflows/pylint.yml modified: .pre-commit-config.yaml

    opened by girip11 26
  • indented magics don't work if they're meant to be indented

    indented magics don't work if they're meant to be indented

    e.g.

    if True:
        %time True
    pass
    

    This will get transformed to

    if True:
    # commented out line
    pass
    

    which isn't valid syntax.

    I'm tempted to say that the fix here would be to replace magics with

    pass  # nbqamagic
    

    and then, in the future, have a less hacky solution

    bug 
    opened by MarcoGorelli 24
  • Add `--nbqa-find` to help the users to troubleshoot issues where nbqa…

    Add `--nbqa-find` to help the users to troubleshoot issues where nbqa…

    … is not able to run the command and raises ValueError: Command not found.

    Changes to be committed: modified: nbqa/main.py modified: nbqa/cmdline.py new file: nbqa/troubleshoot.py modified: tests/test_runtime_errors.py new file: tests/test_troubleshoot.py

    opened by girip11 22
  • Latest hook changes might have a bug: InvalidManifestError

    Latest hook changes might have a bug: InvalidManifestError

    Just after I reinstalled pre-commit (after getting the latest changes) and then I ran precommit run --all or even tried to git commit my changes I get this error:

    An error has occurred: InvalidManifestError:
    ==> File /Users/user/.cache/pre-commit/repo8m9u7jls/.pre-commit-hooks.yaml
    ==> At Hook(id='nbqa')
    ==> At key: types
    ==> At index 0
    =====> Type tag 'jupyter' is not recognized.  Try upgrading identify and pre-commit?
    Check the log at /Users/user/.cache/pre-commit/pre-commit.log
    

    Workaround: uninstall precommit and we can continue to use git commit

    bug good first issue pre-commit 
    opened by neomatrix369 22
  • Github action: adding caching action to the tox.yml github action

    Github action: adding caching action to the tox.yml github action

    On the back of the issue #320 (and original issue #89) amending the following GitHub actions:

    • [x] tox.yml
    • [x] autoupdate-pre-commit-config.yml
    • [x] pre-commit.yml

    Adding the cache action to these github actions via the github action cache@v2.

    enhancement CI/CD performance 
    opened by neomatrix369 22
  • Pylint support. Replace `pass` with `type` for handling magics

    Pylint support. Replace `pass` with `type` for handling magics

    This is required to support pylint. Using pass causes pylint to raise unnecessary pass warnings. Instead if we use builtin function type we are clean of any flake8 and pylint warnings.

    opened by girip11 22
  • QUESTION: how do you measure the complexity of a block of code or blocks of code in the entire notebook?

    QUESTION: how do you measure the complexity of a block of code or blocks of code in the entire notebook?

    I'm raising this just to discuss if there is a way to measure complexity of Python (or other language supported by a notebook)?

    There's https://en.wikipedia.org/wiki/Cyclomatic_complexity that many languages have libraries for, I'm thinking there is one for Python as well.

    In case your other analysis already covers this then please close this. Otherwise, it would be a helpful feature to have.

    Maybe related to #259

    question ideas 
    opened by neomatrix369 22
  • KeyError(1) while parsing output from applying flake8

    KeyError(1) while parsing output from applying flake8

    Hi

    Running nbqA flake8 over notebooks in a set of directories, I encountered a few errors of the form:

    KeyError(1) while parsing output from applying flake8 to ...
    

    I will try to dig into the notebooks to see what the problems appear to be and raise a separate issues as appropriate, but more generally it would be useful if nbQA could trap these errors rather than erroring and then publishing a notice or error file capturing the errors.

    In passing, would it be worth adding to docs a simple example recipe for excluding multiple files with different filename patterns for folk who aren't overly familiar with regex? eg I am using a pattern of the form nbqa flake8 --nbqa-exclude "(.*02.2.*)|(.*07.1.*)|(.*07.2.*)" Part\ *\ Notebooks/*.ipynb with | separated bracketed expressions.

    bug 
    opened by psychemedia 20
  • Useful tool for nbQA: docformatter

    Useful tool for nbQA: docformatter

    The following works with nbQA (1.5.2) and docformatter (1.5.0).

    nbqa docformatter -i example.ipynb
    

    The -i option is needed to tell docformatter to modify the notebook in-place.

    For those using pre-commit, the following configuration can be used:

    repos:
    - repo: https://github.com/nbQA-dev/nbQA
      rev: "1.5.2"
      hooks:
        - id: nbqa
          entry: nbqa docformatter -i
          name: nbqa-docformatter
          alias: nbqa-docformatter
          additional_dependencies: [docformatter==1.5.0]
    

    It might be useful to support docformatter out of the box in nbQA, or to show this example in the documentation. (The documentation already explains how to get custom tools to work, but a working example is always nice to have.)

    Here is an example notebook to try out the above setup: example_nbqa_docformatter.zip

    opened by tovrstra 4
Tool for automatically reordering python imports. Similar to isort but uses static analysis more.

reorder_python_imports Tool for automatically reordering python imports. Similar to isort but uses static analysis more. Installation pip install reor

Anthony Sottile 589 Dec 26, 2022
flake8 plugin to run black for checking Python coding style

flake8-black Introduction This is an MIT licensed flake8 plugin for validating Python code style with the command line code formatting tool black. It

Peter Cock 146 Dec 15, 2022
Pylint plugin for improving code analysis for when using Django

pylint-django About pylint-django is a Pylint plugin for improving code analysis when analysing code using Django. It is also used by the Prospector t

Python Code Quality Authority 544 Jan 6, 2023
A Pylint plugin to analyze Flask applications.

pylint-flask About pylint-flask is Pylint plugin for improving code analysis when editing code using Flask. Inspired by pylint-django. Problems pylint

Joe Schafer 62 Sep 18, 2022
Mypy stubs, i.e., type information, for numpy, pandas and matplotlib

Mypy type stubs for NumPy, pandas, and Matplotlib This is a PEP-561-compliant stub-only package which provides type information for matplotlib, numpy

Predictive Analytics Lab 194 Dec 19, 2022
open source tools to generate mypy stubs from protobufs

mypy-protobuf: Generate mypy stub files from protobuf specs We just released a new major release mypy-protobuf 2. on 02/02/2021! It includes some back

Dropbox 527 Jan 3, 2023
A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.

flake8-bugbear A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycode

Python Code Quality Authority 869 Dec 30, 2022
Automated security testing using bandit and flake8.

flake8-bandit Automated security testing built right into your workflow! You already use flake8 to lint all your code for errors, ensure docstrings ar

Tyler Wince 96 Jan 1, 2023
Utilities for pycharm code formatting (flake8 and black)

Pycharm External Tools Extentions to Pycharm code formatting tools. Currently supported are flake8 and black on a selected code block. Usage Flake8 [P

Haim Daniel 13 Nov 3, 2022
The official GitHub mirror of https://gitlab.com/pycqa/flake8

Flake8 Flake8 is a wrapper around these tools: PyFlakes pycodestyle Ned Batchelder's McCabe script Flake8 runs all the tools by launching the single f

Python Code Quality Authority 2.6k Jan 3, 2023
❄️ A flake8 plugin to help you write better list/set/dict comprehensions.

flake8-comprehensions A flake8 plugin that helps you write better list/set/dict comprehensions. Requirements Python 3.6 to 3.9 supported. Installation

Adam Johnson 398 Dec 23, 2022
Flake8 plugin that checks import order against various Python Style Guides

flake8-import-order A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely tha

Python Code Quality Authority 270 Nov 24, 2022
Flake8 extension for checking quotes in python

Flake8 Extension to lint for quotes. Major update in 2.0.0 We automatically encourage avoiding escaping quotes as per PEP 8. To disable this, use --no

Zachary Heller 157 Dec 13, 2022
Flake8 plugin to find commented out or dead code

flake8-eradicate flake8 plugin to find commented out (or so called "dead") code. This is quite important for the project in a long run. Based on eradi

wemake.services 277 Dec 27, 2022
Flake8 wrapper to make it nice, legacy-friendly, configurable.

THE PROJECT IS ARCHIVED Forks: https://github.com/orsinium/forks It's a Flake8 wrapper to make it cool. Lint md, rst, ipynb, and more. Shareable and r

Life4 232 Dec 16, 2022
A plugin for Flake8 that checks pandas code

pandas-vet pandas-vet is a plugin for flake8 that provides opinionated linting for pandas code. It began as a project during the PyCascades 2019 sprin

Jacob Deppen 146 Dec 28, 2022
Flake8 extension for enforcing trailing commas in python

Flake8 Extension to enforce better comma placement. Usage If you are using flake8 it's as easy as: pip install flake8-commas Now you can avoid those a

Python Code Quality Authority 127 Sep 3, 2022
Tool to automatically fix some issues reported by flake8 (forked from autoflake).

autoflake8 Introduction autoflake8 removes unused imports and unused variables from Python code. It makes use of pyflakes to do this. autoflake8 also

francisco souza 27 Sep 8, 2022
flake8 plugin to catch useless `assert` statements

flake8-useless-assert flake8 plugin to catch useless assert statements Download or install on the PyPI page Violations Code Description Example ULA001

null 1 Feb 12, 2022