Various code cleanup, mostly Python exceptions (rebase)

Should not affect behaviour.

Rebases #1073 somewhat manually: the pattern of commits is somewhat different but broadly the same code should be changed in the same way.