Python 3 compatibility refactoring (requires 3.4+)