Title: Exception notes discarded from TypeError within __hash__() · Issue #149313 · python/cpython · GitHub
Open Graph Title: Exception notes discarded from TypeError within __hash__() · Issue #149313 · python/cpython
X Title: Exception notes discarded from TypeError within __hash__() · Issue #149313 · python/cpython
Description: Bug report Bug description: Context I'm maintaining this library that requires users to construct deeply nested structures that are used as dict keys. To alleviate the annoyance of figuring out where a non-hashable value has been introdu...
Open Graph Description: Bug report Bug description: Context I'm maintaining this library that requires users to construct deeply nested structures that are used as dict keys. To alleviate the annoyance of figuring out whe...
X Description: Bug report Bug description: Context I'm maintaining this library that requires users to construct deeply nested structures that are used as dict keys. To alleviate the annoyance of figuring out...
Opengraph URL: https://github.com/python/cpython/issues/149313
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Exception notes discarded from TypeError within __hash__()","articleBody":"# Bug report\n\n### Bug description:\n\n## Context\n\nI'm maintaining this library that requires users to construct deeply nested structures that are used as dict keys. To alleviate the annoyance of figuring out where a non-hashable value has been introduced into the key structure, I started using dedicated data structures with a `__hash__()`, which adds location information to the exception's notes:\n\n```python\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n@dataclass\nclass KeyStruct:\n name: str\n first: object = field(repr=False)\n second: object = field(repr=False)\n\n def __hash__(self) -> int:\n try:\n h1 = hash(self.first)\n except TypeError as e:\n e.add_note(f\"within {self}.first\")\n raise\n\n try:\n h2 = hash(self.second)\n except TypeError as e:\n e.add_note(f\"within {self}.second\")\n raise\n\n return hash((self.name, h1, h2))\n```\n\nSo when such a structure is used, information about the location of the offending value can be provided:\n\n```python\ns = KeyStruct(\"foo\", 1, KeyStruct(\"bar\", 2, KeyStruct(\"spam\", 3, [])))\ns_dict = {s: \"hello\"}\n```\n\n```\nTraceback (most recent call last):\n File \"/Users/michi/Documents/Projects/Declarative_Python/declarative-python/src/hello.py\", line 43, in \u003cmodule>\n s_dict = {s: \"hello\"}\n ^^^^^^^^^^^^\n File \"/Users/michi/Documents/Projects/Declarative_Python/declarative-python/src/hello.py\", line 34, in __hash__\n h2 = hash(self.second)\n File \"/Users/michi/Documents/Projects/Declarative_Python/declarative-python/src/hello.py\", line 34, in __hash__\n h2 = hash(self.second)\n File \"/Users/michi/Documents/Projects/Declarative_Python/declarative-python/src/hello.py\", line 28, in __hash__\n h1 = hash(self.first)\nTypeError: unhashable type: 'list'\nwithin KeyStruct(name='spam').first\nwithin KeyStruct(name='bar').second\nwithin KeyStruct(name='foo').second\n```\n\nIt is not very beautiful, but very helpful. :)\n\n## The Bug\n\nThe above output is from Python 3.13. The output changes with Python 3.14 (3.14.4 on macOS 14.8.5):\n\n```\nTraceback (most recent call last):\n File \"/Users/michi/Documents/Projects/Declarative_Python/declarative-python/src/hello.py\", line 43, in \u003cmodule>\n s_dict = {s: \"hello\"}\n ^^^^^^^^^^^^\nTypeError: cannot use 'KeyStruct' as a dict key (unhashable type: 'list')\n```\n\nI suspect that the source of this is the improved error messages introduced with https://github.com/python/cpython/issues/132825. If I interpret [this code](https://github.com/python/cpython/pull/132828/changes#diff-b08a47ddc5bc20b2e99ac2e5aa199ca24a56b994e7bc64e918513356088c20aeR2279) correctly, the `dict` and `set` methods that need to hash a key will catch and discard the raised `TypeError` and only re-use the exception message.\n\nIMHO his is unfortunate and I consider it a regression.\n\nI'm not sure what the best way to solve this would be:\n\n- As an experienced Python programmer, I would have expected the implementation of `dict` and `set` to attach the existing exception as `__cause__` on the new exception. That would solve my use case.\n\n- An alternative would be to copy the notes from the old to the new exception. If you consider the notes a part of something I'll call the \"extended exception message\", the code would conceptually replace the exception, modifying, but retaining its \"extended exception message\" in full.\n\n But this sill has the drawback of discarding the original stack trace, which I also consider valuable in many cases.\n\n- Update the passage describing the improvement in [What’s new in Python 3.14](https://docs.python.org/3/whatsnew/3.14.html) to document the change in behavior and provide a workaround. E.g.:\n\n > - Improved error message when trying to add an instance of an unhashable type to a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) or [`set`](https://docs.python.org/3/library/stdtypes.html#set). (Contributed by CF Bolz-Tereick and Victor Stinner in [gh-132828](https://github.com/python/cpython/issues/132828).)\n >\n > (code block)\n >\n > In those instances, the original `TypeError` and its notes and stack trace are replaced. You can raise a subclass of `TypeError` from a `__hash__()` implementation to opt-out of this feature.\n\n AFAICT, the improvement is not documented elsewhere in Python's documentation.\n\n### CPython versions tested on:\n\n3.14\n\n### Operating systems tested on:\n\nmacOS\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-149505\n* gh-161536\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/Feuermurmel","@type":"Person","name":"Feuermurmel"},"datePublished":"2026-05-03T09:25:25Z","url":"https://github.com/python/cpython/issues/149313"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| 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:94db9080-1b28-dfeb-b397-885d011e3990 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E30E:76F02:3B6E59F:4BF559F:6B020387 |
| html-safe-nonce | 861cbfd34ac832bb42efceffadf7a3a7027dc1793a3416822cad727e941fdf75 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFMzBFOjc2RjAyOjNCNkU1OUY6NEJGNTU5Rjo2QjAyMDM4NyIsInZpc2l0b3JfaWQiOiI4MDU2Mzc3MzEzNDg4NjY3NTI3IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | edd24285686023e62ed2538794078947641dc3e1900cc58f3ad67d569cbcad68 |
| hovercard-subject-tag | issue:4371384086 |
| 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/149313/issue_layout |
| twitter:image | https://opengraph.githubassets.com/83a442980aaf733996c9bfb9402169114dc8ac0bf03714aea29cd52d04ae18f5/python/cpython/issues/149313 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/83a442980aaf733996c9bfb9402169114dc8ac0bf03714aea29cd52d04ae18f5/python/cpython/issues/149313 |
| og:image:alt | Bug report Bug description: Context I'm maintaining this library that requires users to construct deeply nested structures that are used as dict keys. To alleviate the annoyance of figuring out whe... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | Feuermurmel |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| 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 | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width