dnanhkhoa / nb_black

A simple extension for Jupyter Notebook and Jupyter Lab to beautify Python code automatically using black.
MIT License
367 stars 41 forks source link

Jupyter notebook cell contents saved in source codes #29

Open PSSF23 opened 3 years ago

PSSF23 commented 3 years ago

Environment:

Description: When running nb-black in jupyter notebooks, the following type of codes would be added to every cell that has been reformatted.

   "outputs": [
    {
     "data": {
      "application/javascript": [
       "\n",
       "            setTimeout(function() {\n",
       "                var nbb_cell_id = 1;\n",
       "                var nbb_unformatted_code = \"%load_ext nb_black\";\n",
       "                var nbb_formatted_code = \"%load_ext nb_black\";\n",
       "                var nbb_cells = Jupyter.notebook.get_cells();\n",
       "                for (var i = 0; i < nbb_cells.length; ++i) {\n",
       "                    if (nbb_cells[i].input_prompt_number == nbb_cell_id) {\n",
       "                        if (nbb_cells[i].get_text() == nbb_unformatted_code) {\n",
       "                             nbb_cells[i].set_text(nbb_formatted_code);\n",
       "                        }\n",
       "                        break;\n",
       "                    }\n",
       "                }\n",
       "            }, 500);\n",
       "            "
      ],
      "text/plain": [
       "<IPython.core.display.Javascript object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],

It repeats the cell contents twice and fortunately would not show anything on the notebook or on the script converted from the notebook. But the text greatly increases the source code sizes and makes notebook changes unfriendly to read.

Could someone help me address this issue? Thanks!

PSSF23 commented 3 years ago

After a little tweaking, I did find this type of codes necessary for showing the formatted cells. But I will leave this issue open for considerations and hope to find a simpler way of integrating javascript in the future.

PSSF23 commented 3 years ago

Unclever Workaround: Before executing anything, use %load_ext lab_black to format all cells (run-all). Then delete the command, restart the kernel, and run everything as normal. This solution would only work for executions that take little effort.