Emacs has basic Python syntax highlighting out-of-the-box with
python-mode
. If you want to do more, there are a few options:
- Jedi
- Elpy
- Flycheck
- LSP
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)))
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:
- Standard library imports.
- Related third party imports.
- 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)))
Formatting with Black
Black is one of my favorite tools for
Python code. It is a PEP8-compliant code formatter, with zero
configuration. Invoke with M-x blacken-buffer RET
.