Fixes for python 3 compatibility.

See also issue #783 and discussion under #1234.