Ported changes from d0dbb13 to Python <2.7