How to comment out a block of Python code in Vim
Comment out your Python block in Vim with visual block mode as follows:
Ctrl + V: activate visual block mode.- Use arrows to highlight the desired lines.
Shift + Iand then#.- Press
Escto comment your block.
Custom efficiency key mapping
Let’s supercharge block commenting with custom mappings in your .vimrc.
- Open
.vimrc::e $MYVIMRC. - Add the following mappings:
- Reload
.vimrcor restart Vim.
Now, toggle comments on the go with Ctrl + c and Ctrl + u. Less hand movement = more time to debate tabs vs spaces.🤭
Dealing with special cases
A toggle to rule them all
Switch between commenting your visual block in and out with a toggle function:
- Implement the toggle:
- Select your block and press
Ctrl + t. Now you've got the power!
Making use of line numbers
Line numbers streamline block selection:
- Enable line numbers:
:set number. - Use line numbers with
:to select a range.
Put the line numbers to work when your code is as long as the arguments you had last Friday about the best Star Wars movie. 🌑💥
Achieve a cleaner code with comments
Quieting with alternative methods
For larger pieces of code (a function, class), consider the power of multiline strings (""") for comments.
- Highlight your block with
V. - Press
Shift + I, then'"""'andEscto "mute" them in style.
Commenting responsibly
While commenting is cool, avoid turning your code into a hash tornado. Pro-tip: Comments should explain why the code does something, not how.
Spring cleaning your comments
Commenting using substitutions
Directly prefix line/s with # without entering visual block using substitution:
"Wait, wasn't # supposed to be a trending topic symbol?" Nope, not here! 🙃
Enhancing your efficiency with motions
Try commenting combined with motion commands:
- Pressing
#➕down arrowcomments out the next line. - Use
Ctrl-vtogether with a motion command (e.g.,%to jump between{}pairs).
Leveraging plugins
If manual tinkering feels old school, try plugins like tpope's vim-commentary:
Being sly as a fox, now look more like a python. 🦊➡️🐍
Was this article helpful?