refactoring python logic