Skip to content

Instantly share code, notes, and snippets.

@chanana
Created June 21, 2022 13:24
Show Gist options
  • Save chanana/2a215a8ef9f1d8d6122120947cb24712 to your computer and use it in GitHub Desktop.
Save chanana/2a215a8ef9f1d8d6122120947cb24712 to your computer and use it in GitHub Desktop.
How to use black in `jupyter` notebooks
  1. Install the GUI extensions module

  2. Go to the Nbextensions tab in your jupyter notebook

  3. Tick code prettify image

  4. Paste the following in the json folding to enable black instead of whatever it’s set to:

{
  "python": {
    "library": "import json\ndef black_reformat(cell_text):\n    import black\n    import re\n    cell_text = re.sub('^%', '#%#', cell_text, flags=re.M)\n    try:\n        reformated_text = black.format_str(cell_text, 88)\n    except TypeError:\n        reformated_text = black.format_str(cell_text, mode=black.FileMode(line_length=88))\n    return re.sub('^#%#', '%', reformated_text, flags=re.M)",
    "prefix": "print(json.dumps(black_reformat(u",
    "postfix": ")))"
  },
  "r": {
    "library": "library(formatR)\nlibrary(jsonlite)",
    "prefix": "cat(toJSON(paste(tidy_source(text=",
    "postfix": ", output=FALSE)[['text.tidy']], collapse='\n')))"
  },
  "javascript": {
    "library": "jsbeautify = require('js-beautify')",
    "prefix": "console.log(JSON.stringify(jsbeautify.js_beautify(",
    "postfix": ")));"
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment