Emacs and Python and eglot and hatch

Posted on Apr 25, 2024

Python has yet another packaging tool, hatch. Here’s how to use it with Emacs.

Create a new project by calling:

hatch new PROJECT_NAME

Testing

Hatch configures new projects to use the pytest runner by default. This runner can be integrated with Emacs using the excellent python-pytest package and setting the python-pytest-executable in .dir-locals.el:

(python-mode . ((python-pytest-executable . "hatch run pytest")))

IPython

To use IPython as your project’s shell first add it to the project’s dependencies (good practice to keep it pinned to a version range):

[tool.hatch.envs.default]
dependencies = [
  "ipython>=8.0",
  ...
]

Now you can start the IPython shell from your terminal by calling hatch run ipython. To have Emacs use this project’s IPython, set python-shell-interpreter using .dir-locals.el:

(nil . ((python-shell-interpreter . "hatch run ipython")
        (python-shell-interpreter-args
         . "-i --simple-prompt --InteractiveShell.display_page=True")))

Org Babel

For data analysis I typically want an org notebook running against some Python dependencies. To run an org babel block within a project’s environment:

(org-mode . ((org-babel-python-command . "hatch run python")))

All Together

Drop this file into your new project’s root as dir-local.el:

((org-mode . ((org-babel-python-command . "hatch run python")))
 (python-mode . ((python-pytest-executable . "hatch run pytest")))
 (nil . ((python-shell-interpreter "hatch run ipython"))))