Fix NameError: free variable 'success' references before assignment in enclosing scope