Open3

JupyterNotebook/JupyterLab チートシート

antyuntyunantyuntyun

差分管理しやすくするための .ipynb -> .py 変換

notebookはdiffがみにくくgitで差分管理しづらいので、.py変換を仕込んでおく。
そうすることで、notebookの変更があった場合には.py化されたものの変化だけをみれば差分が見やすくなる。セル実行番号であったりマジックコマンドを含むセルを変換するときに一工夫必要なので備忘。

参考:
https://stackoverflow.com/questions/57701538/jupyter-notebook-nbconvert-without-magic-commands-w-o-markdown

ノートブックのあるフォルダに nbconvert_config.py を用意

nbconvert_config.py
def comment_magics(input, **kwargs):
     if input.startswith("%"):
         input = "# " + input
     return input
 
 
 # Export all the notebooks in the current directory to the sphinx_howto format
 c = get_config()
 c.NbConvertApp.notebooks = ["*.ipynb"]
 c.Exporter.filters = {"comment_magics": comment_magics}

python_nomagic ディレクトリを作成し、以下2ファイルを用意

python_nomagic/conf.json
 {
     "base_template": "base",
     "mimetypes": {
         "text/x-python": true
     }
 }
python_nomagic/index.py.j2
 {%- extends 'null.j2' -%}
 
 ## set to python3
 {%- block header -%}
 #!/usr/bin/env python3
 # coding: utf-8
 {% endblock header %}
 
 ## remove cell counts entirely
 {% block in_prompt %}
 {% if resources.global_content_filter.include_input_prompt -%}
 {% endif %}
 {% endblock in_prompt %}
 
 ## remove markdown cells entirely
 {% block markdowncell %}
 {% endblock markdowncell %}
 
 {% block input %}
 {{ cell.source | comment_magics | ipython2python }}    
 {% endblock input %}

ここまでで設定完了。
ノートブックの最後のセルに以下コマンドを仕込んでおき、コミット前に実行するようにすれば見やすい.pyが生成される。

!jupyter nbconvert --to python --template my_clean_python_template my_notebook.ipynb
antyuntyunantyuntyun

コードフォーマットのショートカットキー設定

{
    "shortcuts": 
    [
        {
            "command": "jupyterlab_code_formatter:black",
            "keys": [
                "Ctrl E"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}