Formatter for Jupyter notebooks

Introduction

If you are into Data Science or Machine Learning, you have probably come across jupyter notebooks (.ipynb files). The problem I faced when using jupyter notebooks was that the black formatter didn’t work on them. I had tried using the

$ black notebook.ipynb
$ black notebook.ipynb
$ black notebook.ipynb

Enter fullscreen mode Exit fullscreen mode

command many times. This article is meant to help with code formatting in Python Notebooks.


nbQA

So, we will be using a python library called nbQA along with code formatters like Black and isort.

Installation

Install the library using:

$ pip install nbqa
$ pip install nbqa
$ pip install nbqa

Enter fullscreen mode Exit fullscreen mode

Usage

You can use various formatters along with nqba and I will demonstrate how to use a few of them. before trying the formatters, make sure you have installed them already.

black

Format the notebook using black as shown below:

$ nbqa black notebook.ipynb
reformatted notebook.ipynb
All done!
1 files reformatted.
$ nbqa black notebook.ipynb
reformatted notebook.ipynb
All done!   
1 files reformatted.
$ nbqa black notebook.ipynb reformatted notebook.ipynb All done! 1 files reformatted.

Enter fullscreen mode Exit fullscreen mode

isort

Similarly, format the notebook using isort:

$ nbqa isort notebook.ipynb
Fixing notebook.ipynb
$ nbqa isort notebook.ipynb
Fixing notebook.ipynb
$ nbqa isort notebook.ipynb Fixing notebook.ipynb

Enter fullscreen mode Exit fullscreen mode

yapf

$ nbqa yapf --in-place notebook.ipynb
$ nbqa yapf --in-place notebook.ipynb
$ nbqa yapf --in-place notebook.ipynb

Enter fullscreen mode Exit fullscreen mode

autopep8

$ nbqa autopep8 -i notebook.ipynb
$ nbqa autopep8 -i notebook.ipynb
$ nbqa autopep8 -i notebook.ipynb

Enter fullscreen mode Exit fullscreen mode

mdformat

To format the markdown cells in your notebook, use:

$ nbqa mdformat notebook.ipynb --nbqa-md --nbqa-diff
$ nbqa mdformat notebook.ipynb --nbqa-md --nbqa-diff
$ nbqa mdformat notebook.ipynb --nbqa-md --nbqa-diff

Enter fullscreen mode Exit fullscreen mode

doctest

To run tests for iPython notebooks using doctypes:

$ nbqa doctest notebook.ipynb
$ nbqa doctest notebook.ipynb
$ nbqa doctest notebook.ipynb

Enter fullscreen mode Exit fullscreen mode


I hope you liked it. That’s all for this time.

原文链接:Formatter for Jupyter notebooks

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
If you get tired, learn to rest, not to quit.
如果你累了,学会休息,而不是放弃
评论 抢沙发

请登录后发表评论

    暂无评论内容