This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: dict keyerror formatting and tuples
Type: Stage:
Components: Interpreter Core Versions: Python 2.5
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: georg.brandl Nosy List: georg.brandl, lemburg, rhettinger
Priority: normal Keywords:

Created on 2006-10-13 16:00 by lemburg, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
dict-keyerror.diff georg.brandl, 2006-10-14 07:16 patch #1
Messages (4)
msg30242 - (view) Author: Marc-Andre Lemburg (lemburg) * (Python committer) Date: 2006-10-13 16:00
Probably just a minor glitch, but one which caused me
half an hour to track down:

>>> d = {1:'x'}
>>> v = (1,)
>>> d[v]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1

Note the formatting of the error message. It reads '1',
not '(1,)' as you would expect.

The example is constructed. In the code I was
debugging, I didn't know that v was a tuple and thought
it was the integer 1 - so the KeyError itself was
somewhat puzzling.

Only after printing the key I found that the lookup
failed due to a type error.

This happens in Python 2.4 and 2.5.
msg30243 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2006-10-14 07:16
Logged In: YES 
user_id=849994

This is because a tuple as exception "argument" is
automatically unpacked as the arguments on NormalizeException.

Attaching patch that wraps all KeyErrors from dictionaries
in a tuple. (There may be other objects and exceptions where
this must be handled)
msg30244 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2006-11-02 16:18
Logged In: YES 
user_id=849994

Patch was committed as rev. 52535/6.
msg30245 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2006-12-08 17:37
Added a similar fix to Objects/setobject.c in revision 52964.
History
Date User Action Args
2022-04-11 14:56:20adminsetgithub: 44128
2006-10-13 16:00:53lemburgcreate