Python 3 compatibility

The medium-level parts of #358...