classification
Title: Improving KeyError exception
Type: enhancement Stage: resolved
Components: Versions: Python 3.10
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: terry.reedy, zingero
Priority: normal Keywords:

Created on 2020-10-27 20:43 by zingero, last changed 2020-10-30 23:35 by terry.reedy. This issue is now closed.

Messages (2)
msg379801 - (view) Author: Orian Zinger (zingero) Date: 2020-10-27 20:43
Hi all,

As a Python developer, I encountered lots of blurry exception messages in the product logs such as:
<time and date> <process name> <log severity> Failed to do something. Exception: 'some key'

I believe printing the key name without explaining the exception itself is bad (explicit is better than implicit).

Thus, after forking the repository, I added a short explanation about the Exception.
Now, it looks like:

>>> try:
...     {}['some key']
... except Exception as e:
...     print(e)
... 
Missing key: some key

I'm a newbie in a contribution to CPython, so please let me know if the idea behind my commit is good. If not, please explain how can I improve my commit so it'll be pulled later to the main branch.

https://github.com/zingero/cpython/commit/8c9e5d9e16296cee1f3ec05638dd6989dae8b811

Regards,
Orian.
msg380013 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2020-10-30 23:35
Printing an exception is defined as printing the exception message, which currently is e.args[0].  We will not change that as it would break code worldwide.  To print more, the class name can be used directly or as a key into a dict of replacements or replacement functions.

Questions and vague ideas should be directed to python-list.  Fleshed out ideas can go to python-ideas.

>>> {}['d']
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    {}['d']
KeyError: 'd'

>>> try:
	{}['d']
except Exception as e:
	print(e)
	
'd'

>>> try:
	{}['d']
except Exception as e:
	print(e.args)

('d',)

>>> try:
	{}['d']
except Exception as e:
	print(f'{e.__class__.__name__}: {e}')  # Reproduce standard report.

KeyError: 'd'
History
Date User Action Args
2020-10-30 23:35:37terry.reedysetstatus: open -> closed

versions: + Python 3.10
nosy: + terry.reedy

messages: + msg380013
resolution: rejected
stage: resolved
2020-10-27 20:43:09zingerocreate