[Maas-devel] Formatting Python imports in Emacs

Gavin Panella gavin.panella at canonical.com
Thu Nov 20 12:35:56 UTC 2014


If you're an Emacs user, here's a convenient function to reformat Python
imports in the current buffer:

(defun python-format-imports ()
  "Reformats Python module-level imports in the current buffer."
  (interactive)
  (save-excursion
    (save-restriction
      (let ((temp-file (make-temp-file ".python-format-imports.")))
        (unwind-protect
            (progn
              (write-region nil nil temp-file nil 0)
              (call-process "format-imports" nil nil nil temp-file)
              (insert-file-contents temp-file nil nil nil t))
          (delete-file temp-file))))))

I already have format-imports on my PATH; you might want to do that, or
change the call-process line above.

I've bound it to C-c C-f when in python-mode:

(add-hook
 'python-mode-hook
 '(lambda () "Configure python-mode."
    (define-key
      python-mode-map (kbd "C-c C-f")
      'python-format-imports)
    ))

After formatting imports you must save the buffer; it doesn't
automatically save for you, by design. However, if no imports need
formatting your buffer won't be marked dirty.




More information about the Maas-devel mailing list