Emacs: Format Python Code πŸš€

By Xah Lee. Date: .

put this in your Emacs Init File:

(defvar xah-python-formatter-software "black" "value should be string, either β€œblack” or β€œyapf”.")

(defvar xah-python-formatter-black-path "black" "full path or name of python code formatter β€œblack”")

(defvar xah-python-formatter-yapf-path "yapf" "full path or name of python code formatter yapf")

(defun xah-python-format-buffer ()
  "Format the current buffer file by calling `xah-python-formatter-software'.
If buffer is a file, it is saved first.

URL `http://xahlee.info/emacs/emacs/xah_format_python_code.html'
Version 2022-08-25 2022-08-28"
  (interactive)
  (let (($buffFileName (buffer-file-name)))
    (if $buffFileName
        (progn
          (save-buffer)
          (cond
           ((string-equal xah-python-formatter-software "black")
            (shell-command
             (format "%s %s -q" xah-python-formatter-black-path $buffFileName)))
           ((string-equal xah-python-formatter-software "yapf")
            (shell-command
             (format "%s -i %s" xah-python-formatter-yapf-path $buffFileName)))
           (t
            (user-error "`xah-python-formatter-software' should be β€œblack” or β€œyapf”")))
          (revert-buffer t t t))
      (xah-python-format-region (point-min) (point-max))))
  ;; (user-error "buffer should be a file. Use `xah-python-format-region' instead.")
  )

(defun xah-python-format-region (Begin End)
  "Format the current region file using `xah-python-formatter-software'.
The region must be a valid python code.
File is saved first.
URL `http://xahlee.info/emacs/emacs/xah_format_python_code.html'
Version 2022-08-25 2022-08-28"
  (interactive "r")
  (cond
   ((string-equal xah-python-formatter-software "black")
    (shell-command-on-region
     Begin End
     (format "%s - -q" xah-python-formatter-black-path)
     nil
     t))))

requires black or yapf [see Python: Auto Format Code]

Emacs, Format Code