如何在我的 Jupyter 笔记本中配置缩进大小?

How can I configure indentation size in my Jupyter notebooks?

我希望在我的 Jupyter 笔记本中使用 2 个空格而不是 4 个空格的默认缩进大小。我该怎么做?

注意:这不是 How do I change the autoindent to 2 space in IPython notebook 的副本,因为该问题是针对(已弃用)IPython 笔记本而不是(当前)Jupyter 笔记本。

正确的做法是在 bpirvu 对 How do I change the autoindent to 2 space in IPython notebook 的隐藏回答中:

只需编辑 ~/.jupyter/nbconfig/notebook.json。这是一个完整的 notebook.json,其中包括相关设置:

{
  "CodeCell": {
    "cm_config": {
      "indentUnit": 2
    }
  }
}

还有一个更 hacky 的解决方案,在网络上更为流行,可能是因为 Jupyter 文档缺乏关于这个主题的内容,indentUnit 仅在此处提及:http://jupyter-notebook.readthedocs.io/en/latest/frontend_config.html。此解决方案是打开浏览器的 JavaScript 控制台并输入

var cell = Jupyter.notebook.get_selected_cell();
var config = cell.config;
var patch = {
      CodeCell:{
        cm_config:{indentUnit:2}
      }
    }
config.update(patch)

最终会为您编辑 ~/.jupyter/nbconfig/notebook.json