Gilly Gilly - 4 months ago 10
Python Question

Error messages in EAFP style

"It's easier to ask for forgiveness than permission", or EAFP, is a common style in Python, where the coder writes code expecting an error and uses the error handling for expected flow control.

The problem I often find is that this can lead to confusing error messages. Consider this example.

some_dict = {} # oops a bug, this should have 'expected key'

try:
some_dict['optional key'] # expected error
except KeyError:
some_dict['expected key'] # unexpected error


Which yields:

Traceback (most recent call last):
File "eafp.py", line 4, in <module>
some_dict['optional key'] # expected error
KeyError: 'optional key'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "eafp.py", line 6, in <module>
some_dict['expected key'] # unexpected error
KeyError: 'expected key'


Specifically, the unexpected error message references the expected one. This is a trivial example, but in some situations the first error may be completely expected and un-noteworthy, but seems closely related to the real cause of the error and can cause some confusion.

My question is how best to handle this type of issue. Can the first error message be suppressed? Or modified to something less conspicuous?

Answer

For any wondering, I have ended up using the following (rather obvious) solution to remind myself when debugging.

import logging
logger = logging.getLogger(__name__)

some_dict = {} # oops a bug, this should have 'expected key'

try:
    some_dict['optional key'] # expected error
except KeyError as err:
    logger.info('Expected Error: %s', err)
    some_dict['expected key'] # unexpected error
Comments