Please rotate your device
Please rotate
your device
  • Developer Talk: The Merits of Isolation, and Python’s Virtualnv

    Posted by Matt Roberts in May, 2017

    As Technical Director for Kiosk, I’m a big proponent of using the right tool for the right job. Sometimes that means going back to old standards and other times that means breaking new ground. Over the last three years I’ve moved a lot of the behind-the-scenes work at Kiosk from a myriad of different languages to Python. Why Python? Because it doesn’t get in your way, has an active, helpful active community, and Ian Bicking’s supremely awesome virtualenv.

    Everyone on my team has heard me consistently, perhaps even incessantly, beat the drum that is “environment isolation” with developing. I want all our code to behave the same way no matter where it lives and virtualenv is the tool for that job. It allows you to create a folder that contains only the libraries you need for your project, keeping the globally installed packages separate. This way you can be certain that only the code you need is in the environment and ensure that your project behaves the same no matter where it’s running.

    Perhaps the easiest thing about it is the handy activate script that it ships with which ensures you’re only using those libraries. As a bonus, it also helps lazy developers from having to write ~matt/.virtualenvs/radproject/bin/pip install equally-rad-package all the time. It all works great, except for when it doesn’t.

    Overall, I’ve had a great experience with virtualenv and it’s handy shell script, but I recently stumbled across a GitHub gist by Michael Lamb, a.k.a. datagrok, that laid out some convincing reasons not to use the activate script, such as the need for multiple scripts for each supported shell or the fact that the it doesn’t work if you use an unsupported shell. Better yet, he offers some great solutions on how to improve it with a leaner version of his own design. I think it’s very much worth a read and wanted to share as I think that, even five year later, is still relevant.

    I’ve modified Lamb’s inve script a bit to suit my needs. It makes the assumption that your virtual environment folder will be called venv, but it obviates the need to change the VIRTUAL_ENV variable each time you want to launch a new shell. It’s copied below for the curious.

    #!/bin/sh
    BLUE=’\033[0;34m’
    NC=’\033[0m’

    VIRTUAL_ENV=”$PWD/venv”

    if [ ! -d “$VIRTUAL_ENV” ]; then
    echo “No ${BLUE}venv${NC} in current directory.”
    exit
    fi

    export VENV_PROJECT_NAME=${PWD##*/}
    export VIRTUAL_ENV
    export PATH=”${VIRTUAL_ENV// /\\ /}/bin:$PATH”
    unset PYTHON_HOME
    exec “${@:-$SHELL}”

    Interested in a company that codes with consistency? Give Kiosk a call.