Notes on using Python

Notes on using Python

Well, Rich's Excellent Adventures in learning the last 20 years of computing continues. This time with learning how to use Python the right way. Here are some notes:

  • Python versions. There are two major ones, the 2.7 which was frozen back in 2010 and the new Python 3.x. Most systems (like Scons) haven't updated to 3.x and Macs and Ubuntu bundle the 2.7 version. The main differences have to do with handling of unicode and some other changes. But for now 2.7 is a good choice. The so called "user guide" is actually a nice tutorial and overview.

  • Virtualenv. Like most system-wide utilities, this thing utterly breaks because of dependencies. The default is to stuff packages up in a site-wide directory which is a pretty bad idea. The modern way is to use virtualenv to provide a "local" copy of python and all the modules for isolation. After all disk space is cheap these days. This also includes your own copy of pip which let's you install Python modules. What's the best way to get virtualenv, well on ubuntu, its sudo apt-get install -y python-virtuanenv or you can use sudo easy_install virtualenv so that at the top you just have, then when you want to run things, change to the directory and then you can explicitly run things from the env/bin directory or source env/bin/activate to have to all look correct. This is quite similar to the way node.js works as well because all the packages are local. As an aside, there is an additional helped called <a href="">virtualenvwrapper</a> that let's you create and delete and copy python environments.

  • Building python. It is confusing, but Virtualenv should not be in a git which basically means you should as a best practice actually 'build' python and create the environment. The main gotcha is that virtualenv stores absolute paths on machines, so the env directory is not portable. That means you really can't put it in a git and hope that it works. It's another example of not confusing your read-only source environment from the built environment where your code can run. A virtualenv has to be created at build time on any new development machine. One solution people talk about is using the requirements.txt feature which tells python what to load, you set this by running pip freeze which writes that file out and then with scons run pip install -r requirements.txt to get your packages in the built environment.

%d bloggers like this: