Title: AttributeErrors raised in `.keys()` or `.__getitem__()` during `{**mymapping}`are incorrectly masked · Issue #145876 · python/cpython · GitHub
Open Graph Title: AttributeErrors raised in `.keys()` or `.__getitem__()` during `{**mymapping}`are incorrectly masked · Issue #145876 · python/cpython
X Title: AttributeErrors raised in `.keys()` or `.__getitem__()` during `{**mymapping}`are incorrectly masked · Issue #145876 · python/cpython
Description: Bug description: I have a custom Mapping type. I am unpacking it with eg {**mymapping}. If, in either the keys() or the the __getitem__() method, I raise most kinds of errors, such as a ValueError, these are reported correctly. BUT, if I...
Open Graph Description: Bug description: I have a custom Mapping type. I am unpacking it with eg {**mymapping}. If, in either the keys() or the the __getitem__() method, I raise most kinds of errors, such as a ValueError,...
X Description: Bug description: I have a custom Mapping type. I am unpacking it with eg {**mymapping}. If, in either the keys() or the the __getitem__() method, I raise most kinds of errors, such as a ValueError,...
Opengraph URL: https://github.com/python/cpython/issues/145876
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"AttributeErrors raised in `.keys()` or `.__getitem__()` during `{**mymapping}`are incorrectly masked","articleBody":"### Bug description:\n\nI have a custom Mapping type. I am unpacking it with eg `{**mymapping}`. If, in either the `keys()` or the the `__getitem__()` method, I raise most kinds of errors, such as a ValueError, these are reported correctly. BUT, if I raise an AttributeError, then this error isn't reported properly, instead I get `TypeError: 'MyMapping' object is not a mapping`, masking the actual error:\n\n```python\nclass MyMapping:\n def __init__(\n self,\n *,\n raises_on_keys: type[Exception] | None = None,\n raises_on_getitem: type[Exception] | None = None,\n ):\n self.raises_on_keys = raises_on_keys\n self.raises_on_getitem = raises_on_getitem\n\n def __getitem__(self, key):\n if self.raises_on_getitem:\n raise self.raises_on_getitem(\"error in __getitem__\")\n return key * 2\n\n def keys(self):\n if self.raises_on_keys:\n raise self.raises_on_keys(\"error in keys\")\n return [1, 2, 3]\n\n\noptions = [\n None,\n ValueError,\n AttributeError,\n]\noutcomes = []\nfor raises_on_keys in options:\n for raises_on_getitem in options:\n try:\n d = {\n **MyMapping(\n raises_on_keys=raises_on_keys, raises_on_getitem=raises_on_getitem\n )\n }\n outcomes.append((raises_on_keys, raises_on_getitem, \"Success\", d))\n except Exception as e:\n outcomes.append((raises_on_keys, raises_on_getitem, \"Exception\", str(e)))\n\n# format to markdown table\nprint(\"| raises_on_keys | raises_on_getitem | outcome | result |\")\nprint(\"| --- | --- | --- | --- |\")\nfor raises_on_keys, raises_on_getitem, outcome, result in outcomes:\n raises_on_keys_str = raises_on_keys.__name__ if raises_on_keys else \"None\"\n raises_on_getitem_str = raises_on_getitem.__name__ if raises_on_getitem else \"None\"\n print(\n f\"| {raises_on_keys_str} | {raises_on_getitem_str} | {outcome} | `{result}` |\"\n )\n```\n\nRan with `uv run --python 3.14 bug.py`, which resolves to python `3.14.2`. This gives:\n\n| raises_on_keys | raises_on_getitem | error |\n| --- | --- | --- |\n| None | None | `` |\n| None | ValueError | `ValueError: error in __getitem__` |\n| None | AttributeError | `TypeError: 'MyMapping' object is not a mapping` |\n| ValueError | None | `ValueError: error in keys` |\n| ValueError | ValueError | `ValueError: error in keys` |\n| ValueError | AttributeError | `ValueError: error in keys` |\n| AttributeError | None | `TypeError: 'MyMapping' object is not a mapping` |\n| AttributeError | ValueError | `TypeError: 'MyMapping' object is not a mapping` |\n| AttributeError | AttributeError | `TypeError: 'MyMapping' object is not a mapping` |\n\nWhat I would expect is for all of the `TypeError: 'MyMapping' object is not a mapping` errors to actually be `AttributeError: error in keys` or `AttributeError: error in __getitem__` errors.\n\nI assume this is because in the implementation, it does assumes ducktyping, and the raised attribute error is interpreted as \"the passed object doesn't even have a `keys()`/`__getitem__` method\"\n\neg guessing this is how this is currently implemented:\n```python\ntry:\n for key in obj.keys():\n yield key, obj.__getitem__(key)\nexcept AttributeError as e:\n raise TypeError(f\"'{type(obj).__name__}' object is not a mapping\")\n```\n\nWhat I think SHOULD happen:\n\n```python\ntry:\n keys = obj.keys\nexcept AttributeError as e:\n raise TypeError(f\"'{type(obj).__name__}' object is not a mapping\")\nfor key in keys():\n try:\n getter = obj.__getitem__\n except AttributeError as e:\n raise TypeError(f\"'{type(obj).__name__}' object is not a mapping\")\n yield key, getter(key)\n```\n\nEDIT: Actually this should be more performant, only 2 checks, instead of N checks, one per key. (Also, for the record, this includes suggestion to improve the error messages, but that should definitely be a separate PR)\n\n```python\ntry:\n keys = obj.keys\nexcept AttributeError as e:\n raise TypeError(f\"'{type(obj).__name__}' object requires a .keys() method to be used as a mapping\")\ntry:\n getter = obj.__getitem__\nexcept AttributeError as e:\n raise TypeError(f\"'{type(obj).__name__}' object requires a .__getitem__() method to be used as a mapping\")\nfor key in keys():\n yield key, getter(key)\n```\n\n### CPython versions tested on:\n\n3.14\n\n### Operating systems tested on:\n\nmacOS\n\n\u003c!-- gh-linked-prs --\u003e\n### Linked PRs\n* gh-145877\n* gh-145878\n* gh-145906\n* gh-146472\n\u003c!-- /gh-linked-prs --\u003e\n","author":{"url":"https://github.com/NickCrews","@type":"Person","name":"NickCrews"},"datePublished":"2026-03-12T18:03:32.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":16},"url":"https://github.com/145876/cpython/issues/145876"}
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:932aeba2-8cde-9088-2a7e-1c8bcb6b0819 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 8146:3089B4:28931E:376282:6A513FF6 |
| html-safe-nonce | 8a871d203d812c279e5cc0674742ca659362c6dd8c78872e472172bb91a5e1d2 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4MTQ2OjMwODlCNDoyODkzMUU6Mzc2MjgyOjZBNTEzRkY2IiwidmlzaXRvcl9pZCI6IjIyODUxNzIwMjA1OTY1MjI5OTgiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | e6bad21a1d44f2cd3055d37449c352d6dcc64f6239a9bf0937f426634a50de52 |
| hovercard-subject-tag | issue:4066343151 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/145876/issue_layout |
| twitter:image | https://opengraph.githubassets.com/386c805a77653bfeb8480672354cb63314b22c7b731cd0182f53d27a6c2e51c8/python/cpython/issues/145876 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/386c805a77653bfeb8480672354cb63314b22c7b731cd0182f53d27a6c2e51c8/python/cpython/issues/145876 |
| og:image:alt | Bug description: I have a custom Mapping type. I am unpacking it with eg {**mymapping}. If, in either the keys() or the the __getitem__() method, I raise most kinds of errors, such as a ValueError,... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | NickCrews |
| hostname | github.com |
| expected-hostname | github.com |
| None | e840f405b2718e8f2d55aafa9ff27dbce17e29d0c253011d05ea0fea3c78baff |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | e876f00c5723f6080b9d294e4958fd4d506e6faf |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width