Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23218

Why does `dict(id=1, **{'id': 2})` sometimes raise `KeyError: 'id'` instead of a TypeError?

$
0
0

Normally, if you try to pass multiple values for the same keyword argument, you get a TypeError:

In [1]: dict(id=1, **{'id': 2})---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)Input In [1], in <cell line: 1>()----> 1 dict(id=1, **{'id': 2})TypeError: dict() got multiple values for keyword argument 'id'

But if you do it while handling another exception, you get a KeyError instead:

In [2]: try:   ...:     raise ValueError('foo') # no matter what kind of exception   ...: except:   ...:     dict(id=1, **{'id': 2}) # raises: KeyError: 'id'   ...: ---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)Input In [2], in <cell line: 1>()      1 try:----> 2     raise ValueError('foo') # no matter what kind of exception      3 except:ValueError: fooDuring handling of the above exception, another exception occurred:KeyError                                  Traceback (most recent call last)Input In [2], in <cell line: 1>()      2     raise ValueError('foo') # no matter what kind of exception      3 except:----> 4     dict(id=1, **{'id': 2})KeyError: 'id'

What's going on here? How could a completely unrelated exception affect what kind of exception dict(id=1, **{'id': 2}) throws?

For context, I discovered this behavior while investigating the following bug report: https://github.com/tortoise/tortoise-orm/issues/1583

This has been reproduced on Python 3.11, 3.10, and 3.9.


Viewing all articles
Browse latest Browse all 23218

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>