More refactoring of the Python version.