Use pyenv shell instead of pyenv local when running poetry with it

If you are a pyenv and poetry user and need to spawn a virtualenv through poetry, run pyenv shell python-version before running your poetry commands. This post explains why.

By Ace Z. Alba

Published on July 11, 2023, 8:28 pm

Category: tutorial

Tag: corrections, poetry, python, pyenv, django

This update corrects both this personal workflow and this, which I will eventually edit update. In that post, I used pyenv local to specify a project-specific python version.

What I didn't know is that poetry will not recognize this. As gathered from this detailed discussion on github, it seems that poetry will use the python version it was installed with usually instead of the python version active on the shell. So even if you declare the python version of your project explicitly in your config files in poetry, it will not recognize it right away.

As discovered in this answer, only pyenv shell python-version will force poetry to recognize the active python shell set by pyenv. Run pyenv shell python-version first before spawning a virtual environment using poetry.

A new config setting is in the works according to this answer. Run poetry config virtualenvs.prefer-active-python true to make poetry versions 1.2 and above recognize the python version set by pyenv local / a .python-version file. Personally, python shell is the more reliable command at the moment.