-1

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?

2
  • This is hardly more readable than except NameError: print('Name error message')…?! Commented Dec 12, 2023 at 1:06
  • What you're trying is not possible. except is part of the syntax of try, it has to be literally in the code. Functions are not macros, the result is not substituted into the code text. Commented Dec 12, 2023 at 1:08

1 Answer 1

1

Yes, there is! Accessing the type of the exception:

data = { NameError: 'Name error message', IndexError: 'Index error message', } try: foo except Exception as e: error_message = data.get(type(e)) if error_message is not None: print(error_message) 
Sign up to request clarification or add additional context in comments.

4 Comments

kinda ancillary, but in the case of if error_message is not None: is false, the error should probably be raised, instead of silently ignored.
and also, this is going to not really maintain the semantics of except, you'd want to loop over data and check if issubclass(type(e), klass)
so, you probably should do something like except (*data,) as e: but you still have to account for subclasses
@juanpa.arrivillaga Stop being pedantic. The answer is to reproduce exactly what the OP wants.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.