Fixing syntax highlighting for f-strings in Jupyter

Binary Adventures

If you’ve upgrade to Python 3.6 recently and tried to use the new f-strings (or formatted string literals) feature, you might have noticed that the syntax highlighting is broken.

Specifically what happens is that the string, at least for the syntax highlighter, never ends. Your code will still work fine, but it’s a lot harder to see what’s happening.

Here’s an example of the issue: Incorrect syntax highlighting

Luckily, Bede Constantinides managed to isolate the issue. You can either wait for the patch to make its way to a future release of Jupyter, or you can apply a temporary fix (also courtesy of Bede).

Basically, all you need to do is replace two patterns in the main.min.js file, located in site-packages/notebook/static/notebook/js. If you’re using virtualenv, look for the file in <your virtual env folder>/lib/python3.6/site-packages/notebook/static/notebook/js.

After making the necessary modifications, here’s what the same code looks like with correct syntax highlighting: Correct syntax highlighting