python code refactored