Refactoring existing code in Python