Tips & Tricks for Python on Mac

Although Python is probably one of the easiest programming languages to get started with, keeping up with versions and all the imports can often be hastle. Here are a couple of tricks to make your life easier using python on a mac.

1. Pyenv

Pyenv is a tool to manage different python versions in your operating system. To remove existing python installations follow the commands below. Please remove the python path in your ~/.bash_profile file for an existing Anaconda installation. Also, make sure to include eval "$(pyenv init -)" in the ~/.bash_profile file to make sure that pyenv is executed.

# Remove Homebrew Installation
brew uninstall --ignore-dependencies python
# Remove Anaconda Installation
nano ~/.bash_profile
> eval "$(pyenv init -)"
source ~/.bash_profile
rm -rf ~/anaconda3/
rm -rf ~/.conda/
# Other Commands
echo $PATH
which python

Now we are ready to setup pyenv and install the latest python version. If you still have a python version from your system installed make sure to delete the file ~/.python-version that sets the system’s python version.

# Install Pyenv
brew update
brew install readline xz
brew install pyenv
# Install Python Version
pyenv install 3.7.0
pyenv versions
# Set Default Python Version
pyenv global 3.7.0
# Set Local Python Version
pyenv local 2.7.14

Please note that some python packages (i.e. matplotlib) require an installation of python as a framework. To fix this for a specific python version use the command below.

PYTHON_CONFIGURE_OPTS="--enable-framework" pyenv install 3.7.0

2. Virtualenv

Although Pyenv already profides local python version management, keeping track of different package imports can be quite a hastle. Especially, if you need a different version of package (i.e. Django) for different projects. Therefore, virtual environments can be quite helpful for your projects. The commands to get started using virtual environments are listed below.

# Install Virtualenv
pip install virtualenv
# Create Virtual Environment
virtualenv test && cd test
source bin/activate
# Create Python Files
mkdir src && cd src