Emacs: Format Python Code πŸ“œ

By Xah Lee. Date: . Last updated: .

put this in your Emacs Init File:

(defun xah-python-format-buffer (&optional z-begin z-end)
  "Format python code of current buffer or selection.
Respect `narrow-to-region'.
This command requires external command β€œblack”.

URL `http://xahlee.info/emacs/emacs/xah_format_python_code.html'
Created: 2022-08-25
Version: 2026-04-23"
  (interactive
   (let (xbeg xend)
     (setq xbeg (if (region-active-p) (region-beginning) (point-min)))
     (setq xend (if (region-active-p) (region-end) (point-max)))
     (list xbeg xend)))
  (let (xbeg xend)
    (progn (setq xbeg (if z-begin z-begin (if (region-active-p) (region-beginning) (point-min))))
           (setq xend (if z-end z-end (if (region-active-p) (region-end) (point-max)))))
    (let ((xpos (point))
          (xoutbuf (get-buffer-create "*xah-python-format output*"))
          xexitstatus)
      (with-current-buffer xoutbuf (erase-buffer))
      (setq xexitstatus
            (call-process-region xbeg xend "black" nil xoutbuf nil "-" "-q"))
      (if (eq 0 xexitstatus)
          (progn
            (delete-region xbeg xend)
            (insert-buffer-substring xoutbuf)
            (goto-char xpos)
            (kill-buffer xoutbuf))
        (progn
          (display-buffer xoutbuf)
          (error "error xah-python-format-buffer"))))))

requires python black. [see Python: Format Code]

Emacs, Format Code