Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I block comment code in the IPython notebook?

I have defined a function in an IPython notebook and would like to be able to block comment a section of it. Intuitively, I'd expect to be able to highlight a section of code, right click and have an option to comment out the selection but this has not been implemented.

Is there a way to do this?

like image 332
WalkingRandomly Avatar asked Oct 11 '13 12:10

WalkingRandomly


People also ask

How do you block comments in a Jupyter notebook?

All you need to do, is select all the lines you want to comment and press Ctrl + / as shown in below video.

How do I block comment code?

The leading characters // are added to the beginning of each line when commenting one or more lines of code. You can also block comment multiple lines of code using the characters /* */ .

How do you block comments in Python?

To create a comment block in Python, prepend a #(octothorpe) to each line. Then, use the comment block in the code to prevent the execution while testing the code. Most existing programming languages have syntax for block comments that cross multiple text lines.

How do you comment out a whole section in a Jupyter notebook?

To comment out a block of code – First, we need to select all those lines which we want to comment out. Next, on a Windows computer, we need to press the ctrl + / key combination to comment out the highlighted portion of the code.


1 Answers

Default solution

In IPython 2.x and 3.x (cmd|ctrl)-/ works but requires an english (american) keyboard layout, see https://github.com/ipython/ipython/pull/3673.

Other keyboard layouts

In case you have a non-english keyboard layout, you can define a custom keybinding for the codemirror editor via your custom.js. To this end add e.g. the following lines

define([     'base/js/namespace',     'base/js/events'     ],     function(IPython, events) {         events.on("app_initialized.NotebookApp",             function () {                 IPython.Cell.options_default.cm_config.extraKeys = {"Ctrl-," : "toggleComment"};             }         );     } ); 

to use Ctrl+, to toggle (block) comments. I use this with a german keyboard layout and IPython 3.0. The previous solution (see edits) worked fine with chrome, but not with firefox.

Old solution (IPython 1.x)

If you are using IPython 1.x you can try the comment-uncomment.js from https://github.com/ipython-contrib/IPython-notebook-extensions - I haven't tried this yet, but I guess its a good start.

like image 108
Jakob Avatar answered Sep 30 '22 04:09

Jakob