Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using earlier version of python with poetry

What is the process for setting up a project and using an earlier version of Python which has not been installed as a system-wide binary?

Ideally, poetry add <package> should install to that previous version of python, and poetry shell should open up a virtual environment with the correct version.

I have tried:

mkdir myproj
cd myproj

eval "$(pyenv init -)"
pyenv install 3.8.9
pyenv local 3.8.9

poetry init --no-interaction --python="3.8.9"
poetry env use 3.8.9
poetry add numpy

echo '
import sys
print(sys.version)

import numpy
print(numpy.__version__)
' > main.py

poetry shell
eval "$(pyenv init -)"
python main.py

But this gives:

3.8.9 (default, May  1 2021, 22:43:00)
[GCC 10.2.0]
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    import numpy
ModuleNotFoundError: No module named 'numpy'

...indicating that the correct version of python ran (as expected), but that the package was not installed to python 3.8.9. Indeed:

λ ls "$(poetry env info --path)/lib"
python3.9

λ grep "version_info" "$(poetry env info --path)/pyvenv.cfg"
version_info = 3.9.4.final.0
like image 490
Mateen Ulhaq Avatar asked May 02 '21 05:05

Mateen Ulhaq


People also ask

Can poetry manage Python versions?

Since version 1.2, Poetry no longer supports managing environments for Python 2.7.

What Python does poetry use?

Learn about vigilant mode. Poetry by default just uses the system Python, even if that is not supported by the version specifier in pyproject. toml. Poetry prints > The currently activated Python version 3.9.

Does poetry use Virtualenv?

virtualenvs. If not set explicitly, poetry by default will create virtual environment under {cache-dir}/virtualenvs or use the {project-dir}/. venv directory when one is available. If set to true , the virtualenv will be created and expected in a folder named .


1 Answers

Turns out that everything works correctly for pyenv 2.x (released just recently). The new instructions indicate that we now need to update $PATH as well with $HOME/.pyenv/shims. This is done via:

eval "$(pyenv init -)"
eval "$(pyenv init --path)"

Poetry now correctly installs python3.8 to $(poetry env info --path)/lib rather than python3.9 (?!). It is unclear why poetry was doing that in the first place, but I assume it was a pyenv 1.x bug.


Full example:

eval "$(pyenv init -)"
eval "$(pyenv init --path)"

mkdir myproj
cd myproj

pyenv install 3.8.9
pyenv local 3.8.9
poetry init --no-interaction --python="3.8.9"
poetry env use 3.8.9
poetry add numpy

echo '
import sys
print(sys.version)

import numpy
print(numpy.__version__)
' > main.py

poetry run python main.py

Output:

3.8.9 (default, Sep 14 2021, 18:39:31)
[GCC 11.1.0]
1.21.2
like image 67
Mateen Ulhaq Avatar answered Oct 03 '22 17:10

Mateen Ulhaq