;; The following code (select-current-line) is due to Xah Lee, see http://lists.gnu.org/archive/html/help-gnu-emacs/2010-12/msg01183.html
(defun select-current-line ()
"Select the current line"
(interactive)
(beginning-of-line) ; move to end of line
(set-mark (line-end-position)))
Now we can define the following function (which uses the idea from https://stackoverflow.com/a/9697222/ due to Gerstmann but it is not identical to that answer).
(defun comment-or-uncomment-line-or-region ()
"comment-or-uncomment-line-or-region"
(interactive)
(save-excursion (if (region-active-p) (comment-dwim nil)
(select-current-line) (comment-dwim nil)
)))
Now you can define a shortcut for it:
(eval-after-load "python"
'(define-key python-mode-map (kbd "M-;") #'comment-or-uncomment-line-or-region))
M-x comment-region
orM-x uncomment-region
work?M-;
is a shortcut forM-x comment-dwim
. DoM-x describe-binding
and make sure thatM-;
is binded tocomment-dwim
.