How to manage Python versions and packages

2024-10-05

Ensure direnv is installed. Then run:

python3.11 -m venv .venv  # 1 - latest version
echo -e "export VIRTUAL_ENV=.venv\nlayout python3" > .envrc \
    && direnv allow
python -m pip install --upgrade pip
touch .env .env.example

And add this to your .zshrc:

function pipi {
  if [ $# -lt 1 ]; then
    echo "Usage: $funcstack[1] <package-name>"
    return 1
  fi

  if [ ! -f requirements.txt ]; then
    echo "Error: requirements.txt file not found in the current directory."
    return 1
  fi

  python -m pip install $1
  python -m pip freeze > requirements.txt
}

function virtualenv_info {
    [ $VIRTUAL_ENV ] && echo '('`basename $VIRTUAL_ENV`') '
}

PROMPT+=' $(virtualenv_info)'  # or PS1 if that's what you use

Add new packages with:

pipi requests

Now you have a virtual env set up with:

  • minimal dependencies
  • minimal failure modes
  • no uncomfortable questions like ‘How do I install poetry/pdm/etc before I have a virtual env set up?’
  • automatic virtual env activation by cd’ing into the folder

For more details check out: