I'm currently trying to write a function that'll make walls of except blocks more human-readable, but when a program tries to dynamically execute them with exec(), Python returns a syntax error.
def error_handling(errors_messages): output = '' for error in errors_messages: output = (output + 'except ' + error + ':\n' ' print(\"' + errors_messages[error] + '")\n') return output try: # stuff goes here pass exec(error_handling({ 'NameError': "Name error message", 'IndexError': "Index error message" })) Adding a dummy error in front of the exec() function doesn't seem to help much, as it then seems to forget about the try block.
Is there a better way to do this?
except NameError: print('Name error message')…?!exceptis part of the syntax oftry, it has to be literally in the code. Functions are not macros, the result is not substituted into the code text.