A Python Walkabout – Episode 2

This is part of a series of posts on learning Python and building a Python web service.

Environment

Python has a similarity to Node.js: there are different versions of the language/runtime and not all apps will work with every release. And sometimes you need to develop against a different version, but it’s not possible to have multiple versions active simultaneously. For Node there are tools like nvm or nvm-windows that solve this problem, allowing you to switch which version of Node is active at any time.

Python devs run into this a lot. Libraries or tools may not work with a new version of the language. Or you have to maintain an app that only works with an older version, but you also need to write new code using the current version. The suggested way to handle this is to create virtual environments in each project directory. Each environment includes a directory that contains the version of the Python interpreter you want, plus the dependencies for just that project, plus assorted helper scripts/tools. A different project in a different directory can have its own virtual environment with all different stuff. There is also a tool for Windows named pyenv-win that helps manage having different version of Python installed on the same machine, though I decided not to use it for now since I didn’t need it.

So that all made sense and I planned to create one for the Music Browser API. But again, that lead to the question of which tool to use to create one (another Node similarity: a dearth of tools available to do any particular thing). Python itself includes a module to create these environments named venv. It does the job but some brief web searching suggested other, better choices. I eventually picked virtualenv since it had good features and made things easy. It works great, though I ended up building, destroying, and re-building the environment for the Music Browser API over and over, as various things I was trying went wrong (more on that here).

Postscript:
An interesting thing I learned later is virtulenv comes bundled with PyCharm, which is the IDE I’m using. And when you create a new Python app it uses it to create a virtual environment for you. So running virtualenv by itself isn’t even necessary, though it’s good to know how to do it.