Emacs: Format Python Code πŸ“œ

By Xah Lee. Date: . Last updated: .

put this in your Emacs Init File:

(defun xah-python-format-buffer ()
  "Format the current buffer file.
Calls the external program β€œblack”.
Buffer is saved first.

URL `http://xahlee.info/emacs/emacs/xah_format_python_code.html'
Created: 2022-08-25
Version: 2025-07-08"
  (interactive)
  (when (not (buffer-file-name)) (user-error "buffer %s is not a file." (buffer-name)))
  (when (buffer-modified-p) (save-buffer))
  (let ((xoutbuf (get-buffer-create "*xah-python-format output*"))
        xexitstatus)
    (with-current-buffer xoutbuf (erase-buffer))
    (setq xexitstatus (call-process "black" nil xoutbuf nil buffer-file-name "-q"))
    (if (eq 0 xexitstatus)
        (progn
          (kill-buffer xoutbuf)
          (revert-buffer t t t))
      (progn
        (display-buffer xoutbuf)
        (error "error xah-python-format")))))

requires python black. γ€”see Python: Format Code〕

Emacs, Format Code