Emacs: Format Python Code πŸš€

By Xah Lee. Date: . Last updated: .

put this in your Emacs Init File:

(defvar xah-python-formatter-software
  "black"
  "Value is a string, either black or yapf.
Used by `xah-python-format-buffer` etc.")

(defvar xah-python-formatter-black-path
  "black"
"Full path or name of python code formatter black.
Used by `xah-python-format-buffer` etc.")

(defvar xah-python-formatter-yapf-path
  "yapf"
  "Full path or name of python code formatter yapf.
Used by `xah-python-format-buffer` etc.")

(defun xah-python-format-buffer ()
  "Format the current buffer file.
Calls the program in variable `xah-python-formatter-software'.
also check
variable `xah-python-formatter-black-path'
or
variable `xah-python-formatter-yapf-path'

If buffer is a file, it is saved first.

URL `http://xahlee.info/emacs/emacs/xah_format_python_code.html'
Created: 2022-08-25
Version: 2024-10-03"
  (interactive)
  (if buffer-file-name
      (progn
        (save-buffer)
        (cond
         ((string-equal xah-python-formatter-software "black")
          (shell-command
           (format "%s %s -q" xah-python-formatter-black-path buffer-file-name)))
         ((string-equal xah-python-formatter-software "yapf")
          (shell-command
           (format "%s -i %s" xah-python-formatter-yapf-path buffer-file-name)))
         (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'
Created: 2022-08-25
Version: 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: Format Code〕

Emacs, Format Code