Basic Python config

Emacs has basic Python syntax highlighting out-of-the-box with python-mode.

Autocomplete

Jedi

Jedi is a Python completion framework.

(require 'jedi)
(add-hook 'python-mode-hook (lambda ()
                  (setq jedi:complete-on-dot t)
                  (jedi-mode)
                  (jedi:setup)
                  (company-mode)))

Elpy

Elpy is a more powerful autocompletion/navigation framework, and it can use Jedi as a backend completion tool (this is what I do when I use Elpy). Elpy uses flymake by default, but can be configured to work with flycheck as well:

(when (require 'flycheck nil t)
  (setq elpy-modules (delq 'elpy-module-flymake elpy-modules))
  (add-hook 'elpy-mode-hook 'flycheck-mode))

It is possible to configure Elpy to use Python3 as the backend interpreter, and to use jedi for completion:

(require 'elpy)
(require 'jedi)
(when (require 'flycheck nil t)
  (setq elpy-modules (delq 'elpy-module-flymake elpy-modules))
  (add-hook 'elpy-mode-hook 'flycheck-mode))
(add-hook 'python-mode-hook (lambda ()
                  (setq elpy-rpc-backend "jedi")
                  (setq elpy-rpc-python-command "python3")
                  (setq python-shell-interpreter "python3")
                  (setq jedi:complete-on-dot t)
                  (jedi:setup)))

Syntax checking

Pylint

Flycheck defines a python-pylint checker to use for checking against PEP8 style. No special configuration is required (as far as I am aware), as long as the pylint Python package is installed in the current environment. This does a pretty good job at keeping you honest as you write, although it can get annoyingly pedantic at times (this is considered a feature by many Pythonistas).

MyPy

MyPy is a static typing package that performs static analysis on your code to make sure that you're being safe in Python's dynamic typing environment. It can be configured as an additional checker using flycheck-pycheckers, or run manually in the terminal.

Import sorting

PEP8 defines import ordering as:

  1. Standard library imports.
  2. Related third party imports.
  3. Local application/library specific imports.

With a blank line in between each group. You can have Emacs autosort your imports by using the py-isort package.

(add-hook 'python-mode-hook (lambda ()
                  (add-hook 'before-save-hook 'py-isort-buffer nil 'local)))

References