pythonpython-3.xvirtualenvpython-packaginghatch

Python Hatch: `ERROR: Package 'hatch-demo' requires a different Python: 3.10.5 not in '<3.10,>=3.9'`


hatch new "Hatch Demo"
cd hatch-demo

In pyproject.toml, I set:

requires-python = ">=3.9,<3.10"

I run:

hatch env create

I get:

ERROR: Package 'hatch-demo' requires a different Python: 3.10.5 not in '<3.10,>=3.9'

I have both Python 3.9 and 3.10 installed via Homebrew. Python 3.9.13 is set as the default.

python3 --version
Python 3.9.13

How do I fix this so that Hatch will use Python 3.9.x when creating the environment for this project?


Solution

  • The way it works with hatch (as far as I understand) is that the (default) environment is configured independently from the project requirements (those are for building the packages sdist/wheel/...). By default it will use the first python interpreter found on your $PATH (according to this), which I'm guessing is 3.10.5 in this case. This is independent of the python executable hatch itself is run with.

    The solution then is to tell hatch in the pyproject.toml which python version to create the default environment with as described in the official docs:

    [project]
    name = "myproject"
    requires-python = ">=3.9,<3.10"
    ...
    
    [tool.hatch.envs.default]
    python="3.9"  # <--
    
    # other optional environment configuration, e.g.
    path = ".venv"
    dependencies = [
      "black",
      "pytest",
      ...
    ]
    

    For this, the requested version needs to be installed on the system. It can also be an absolute path to the python executable.

    Then issuing a hatch env create or a hatch run myfile.py should create a virtual environment with the correct python version, project dependencies and the virtual environment dependencies.