rogulski.it

My name is Piotr, a passionate pythonista and this is my blog!

    Handle python versions and virtualenv like a pro! (including Apple M1)

    Posted at — May 2, 2022

    Seeing this post you already know what is a virtualenv and why it is helpful to use it.

    In this post, I would like to share how to install it and navigate though projects faster and easier!

    Handling different Python versions with pyenv

    In this case, I recommend to already use pyenv - a simple python version management tool.

    1. Install pyenv

      brew install pyenv
      
    2. Install preferred Python version

      pyenv install -v 3.10.3
      
    3. Access all python versions:

      cd ~/.pyenv/versions/
      

    Handling virtualenv using pyenv-virtualenv

    One of the best ways which I found to handle virtualenv with different versions of Python on Apple Macbook with M1 silicon is via pyenv-virtualenv.

    1. Install pyenv-virtualenv

      brew install pyenv-virtualenv
      
    2. Create a virtualenv (it will always create in .pyenv/versions directory)

      pyenv virtualenv 3.10.3 my-virtual-env-3.10.3
      
    3. List all virtualenvs

      pyenv virtualenvs
      
    4. Activate virtualenv

      pyenv activate my-virtual-env-3.10.3
      
    5. Deactivate virtualenv

      pyenv deactivate
      

    Not many people are aware of this nice alternative to easily navigate through many virtualenv and python projects. I have discovered (virtualenvwrapper)[https://virtualenvwrapper.readthedocs.io/en/latest/] many years ago, and I’m still using it till today.

    1. Install virtualenvwrapper

      pip install virtualenvwrapper
      
    2. Setup environment variables in your .bashrc or .zshrc

      export WORKON_HOME=$HOME/.virtualenvs
      export PROJECT_HOME=$HOME/Devel
      export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
      export VIRTUALENVWRAPPER_VIRTUALENV=/Users/rglsk/Library/Python/3.8/bin/virtualenv
      source /Users/rglsk/Library/Python/3.8/bin/virtualenvwrapper.sh
      
    3. Create virtualenv (You can use any Python version from pyenv)

      mkvirtualenv mkvirtualenv -p ~/.pyenv/versions/3.10.3/bin/python3 my-virtual-env-3.10.3
      
    4. Activate virtualenv

      workon my-virtual-env-3.10.3
      
    5. Enter virtualenv and project from any location

      cdvirtualenv
      
    6. Deactivate virtualenv

      deactivate
      

    Summary

    I know that there are other ways like conda to set up Python virtualenv (including Apple M1).

    Tools I have described are working well for me. For my local development I’m using Pycharm that is having easy integration with any Python interpreter.

    I would recommend testing couple of different ways to find the one you will love and use!