This is what works for me currently. Note that the direnv wiki addresses various methods for managing python with direnv: https://github.com/direnv/direnv/wiki/Python
- Install direnv and pyenv. I use homebrew for these tasks. There may be setup and/or shell integration steps for these tools that I'm omitting (I can't remember), so check their docs.
- Determine the python version(s) you will likely be using and install them with
pyenvat the command line (i.e., in Terminal).pyenv versionswill show you the versions already locally installed.pyenv install --listwill show you all the versions available to install.pyenv install 3.12.4will install that particular version for use on your local system.
- Using the Terminal, move to or create and move to a directory that will contain your python project (package or script or whatever).
- Configure the directory using
direnv. To specify the python version you want to use as the virtual environment for python work in that directory (and its children), create a.envrcfile and put the linelayout pyenv 3.12.5(or whatever python version you need) and save the file. - Follow the
direnvprompt at the command line to "Rundirenv allowto approve its content." - The first time you do this,
direnvwill invokepyenvto set up a python virtual environment inside a.direnvsubfolder it creates for this purpose. - Subsequently, when you
cdinto this directory,direnvwill activate the virtual environment. When youcdout of this directory,direnvwill deactivate the virtual environment. - When in the directory with the virtual environment activated, you can add packages and do updates in the normal ways, e.g.,
pip install -U pip. - Recent versions of Visual Studio Code correctly detect and use your
direnv-managed virtual environment if started from the command line in the directory usingcode ..