backport some of regebros modern python idiom changes from his regebro-refactor branch