Why do you need Python virtual environment? Because we don't want to messed up Python installed with the MacOS.
- Of course you are a Python Developer.
- Work with multiple Python versions.
- Work with multiple Python projects.
- Work with multiple Python project prototypes.
- Using MacOS.
PyENV make it easy to manage multiple Python version, so let install it with brew.
brew install pyenv
After installation, check your terminal for instruction to update either your
~/.bash_profile
or ~/.zshrc
. Follow the instruction and restart your
terminal.
Now, we should be able to install Python version.
pyenv install 3.9.0
pyenv install 3.8.6
# If you want to see which versions are available
pyenv install --list
Now you are leave with three options either to make your new Python version as
global
, local
or on demand.
pyenv global 3.9.0
Now every where when you run command python -V
you should see the version is
3.9.0.
mkdir project
cd project
pyenv local 3.8.6
Now when ever you shell to project
directory your python version will changed
to 3.8.6.
pyenv shell 3.8.6
Now your Python version is 3.8.6, this command create a session if you restart your terminal it will change to the global version.
Virtual environment act as another layer on top on PyEnv, because we do not want to install dependency directly to Python version because sometime we have different projects that use the same Python version but different dependency. Example:
- Project A using Python 3.9.0 with Django 2.2
- Project B using Python 3.9.0 with Django 3.3
So let says we have a prototype project that using python 3.8.6.
mkdir prototype
cd prototype
pyenv shell 3.8.6
# Virtual Environment is exception to install directly to python
pip install virtualenv
virtualenv venv
The downsize about virtualenv
is that you need to activate before using it.
prototype $ source venv/bin/activate
(venv) prototype $
# (venv) Indicated that venv is activated
The reason I prefer virtualenv
over pyenv-virtualenv
because when working
with many prototype project and if I want to delete that project and since
virtualenv
is just create virtual environment directory, so I can just delete
the project directory and the virtual environment is also gone.
On the other hand with pyenv-virtualenv
, it create a separated virtual
environment to delete the project I would also need to run
pyenv uninstall prototype
.
Also if you using PyCharm, it will automatically detect interpreter using
virtualenv
.