Python 3 port, retaining 2.7 compatibility