;; 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"
(beginning-of-line) ; move to end of line
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 ()
(save-excursion (if (region-active-p) (comment-dwim nil)
(select-current-line) (comment-dwim nil)
Now you can define a shortcut for it:
'(define-key python-mode-map (kbd "M-;") #'comment-or-uncomment-line-or-region))