Choose your Python version with pyenv
Pyenv allows you to easily manage multiple Python versions on your system, which is particularly useful when working with different Django projects that require specific versions of Python.
You can easily install pyenv with curl:
curl https://pyenv.run | bash
Then add the following lines to your .bashrc
:
export PYENV_ROOT="$HOME/.pyenv"
command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
To use a specific python version for your project, execute
pyenv install 3.11.3
pyenv local 3.11.3
This will create a .python-version
file in your project’s director, that specifies the currently used python version.
You can verify by executing python --version
.
Manage your dependencies with poetry
Dependency management is important because external libraries can change over time, and upgrading them without proper management can potentially crash your application. Poetry incorporates everything you need to isolate your project and manage your dependencies.
You can install poetry outside your project’s directory with
curl -sSL https://install.python-poetry.org | python3 -
Here are some useful commands that you will always come across:
- With
poetry init
you can easily generate a newpyproject.toml
file inside the current directory, that keeps track of the project dependencies - With
poetry add <package-name>
you can add a new package to yourpyproject.toml
file and immediately install it in your virtual environment - With
poetry shell
you activate your virtual environment and run it isolated from other projects - With
poetry export
you can write your dependencies in a format that can be easily installed with pip
🤫 Tip
Create a
requirements/
directory to separate development, test and production requirements.
TL;DR
Here is a quick run-through on how to set up a new Django project after having successfully installed pyenv and poetry:
Further Reading
- RealPython: More details on how to work with poetry
- Boring Python: dependency management: Great article that describes how to work with tools like “pip” and “venv” and what you have to look out for
- Youtube: Bootstrapping Your Local Python Environment:
Just a regular video discussing python environments, but I like this one: Don’t use
sudo
when you set up your python envrionment