Title: Add public functions to dataclasses to correctly identify methods and features · Issue #157314 · python/cpython · GitHub
Open Graph Title: Add public functions to dataclasses to correctly identify methods and features · Issue #157314 · python/cpython
X Title: Add public functions to dataclasses to correctly identify methods and features · Issue #157314 · python/cpython
Description: Feature or enhancement Proposal: There are a few places both in the stdlib and in third party packages where tools attempt to discover specific features of how dataclasses are constructed. Currently these either rely on leaky internals o...
Open Graph Description: Feature or enhancement Proposal: There are a few places both in the stdlib and in third party packages where tools attempt to discover specific features of how dataclasses are constructed. Currentl...
X Description: Feature or enhancement Proposal: There are a few places both in the stdlib and in third party packages where tools attempt to discover specific features of how dataclasses are constructed. Currentl...
Opengraph URL: https://github.com/python/cpython/issues/157314
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Add public functions to dataclasses to correctly identify methods and features","articleBody":"# Feature or enhancement\n\n### Proposal:\n\nThere are a few places both in the stdlib and in third party packages where tools attempt to discover specific features of how dataclasses are constructed. Currently these either rely on leaky internals or will behave incorrectly in certain cases, or both.\n\nI'd like to both make it possible to stop leaking those internal details while also making the discovery more accurate.\n\nProposal:\n\n1) **Add a `__generated_for_dataclass__` attribute to methods generated by dataclasses** \n * This would hold the class the method was generated for\n * Note that this would not include shared functions like `__replace__` which are attached to dataclasses but are not generated for a specific class\n * Adding a `True/False` flag was proposed back in [the issue that added pprint repr replacement support](https://github.com/python/cpython/issues/87246#issuecomment-1093900950), this extends that idea to also identify which class a method was generated for which gives more useful information[^1]\n2) **Add a public `generated_for_dataclass`[^2] function to retrieve this attribute** \n * This would return `None` if the method is not a generated dataclass method\n3) **Add an `is_frozen` public function** to detect if a class is actually a frozen dataclass\n * The current implementation would check that `generated_for_dataclass(cls.method) is cls` for both `__setattr__` and `__delattr__`\n * This is both a convenience function and future-proofing if the implementation of frozen-ness changes\n\nIn the linked discuss thread I also mentioned adding a `requires_decorator` to `is_dataclass` to identify if a class has been decorated and doesn't just inherit from a dataclass along with making `_is_dataclass_instance` public and adding a matching `is_dataclass_type`. These additions could be used to simplify some existing checks but aren't necessary to resolve the logic issues. As such I'm leaving them out unless it's considered worthwhile to include them.\n\n---\n\nExamples of issues this intends to resolve:\n\n1) Attempts to detect and replace a dataclass `__repr__`:\n\n- [pprint](https://github.com/python/cpython/blob/36c7440c480da622735788af656c728af28cd9eb/Lib/pprint.py#L208-L215)\n * This relies on dataclasses not cleanly renaming the `__repr__` function and leaking the name of the internal `__create_fn__` function through the recursive_repr wrapper\n * This prevented dataclasses from renaming the internal function in [a previous PR](https://github.com/python/cpython/pull/110851#issuecomment-1768502273)\n * A change that would no longer leak the internal name would also break this (I discovered this while testing changes for lazy method generation)\n- [enum](https://github.com/python/cpython/blob/36c7440c480da622735788af656c728af28cd9eb/Lib/enum.py#L993-L999)\n * This only checks if `repr=True` is in the params and doesn't check if the `__repr__` method is actually generated by dataclasses and will replace any `__repr__` method on a dataclass\n * As a dataclass, defining the `__repr__` by hand should be treated the same as setting `repr=False` but this isn't the case for enum \n- [rich](https://github.com/Textualize/rich/blob/9d8f9a372cc5916fd4781fec207ced7ddac2f08f/rich/pretty.py#L70-L87)\n * This checks for `reprlib.py`'s path in `__code__.co_filename`\n * **Any** `__repr__` function on a dataclass that uses `recursive_repr` will be replaced\n * Unlike the 2 stdlib cases, this can't rely on being kept in sync with changes to `dataclasses` due to failing stdlib tests\n\nThese could all use `generated_for_dataclass(cls.__repr__)` to both identify if a `__repr__` is replaceable and get the correct class to use for retrieving the matching `fields`.\n\n---\n\n2) Current attempts to detect frozenness:\n\nThere are a number of tools that look at `cls.__dataclass_params__.frozen` to try and detect if a class is a frozen dataclass, here's an example from [pytorch](https://github.com/pytorch/pytorch/blob/2b1d72fc614c57d5ebe70ebaf22da2abaf11a3d4/torch/_dynamo/utils.py#L5537-L5548) and [other examples from a search](https://github.com/search?q=__dataclass_params__.frozen+language%3APython&type=code).\n\nThis logic will fail if `__setattr__` or `__delattr__` have been replaced in an undecorated subclass.\n\n```python\nfrom dataclasses import dataclass, is_dataclass\n\n@dataclass(frozen=True)\nclass Frozen:\n a: int = 42\n\nclass UnFrozen(Frozen):\n __setattr__ = object.__setattr__\n __delattr__ = object.__delattr__\n\nex = UnFrozen()\nprint(is_dataclass(ex)) # True\nprint(ex.__dataclass_params__.frozen) # True\nex.a = 1 # Not actually frozen\n```\n\n[^1]: For example if you want to replace the `__repr__` function, it tells you which class to use for `fields(cls)` to generate the correct method\n[^2]: Open to a different name if there's a better suggestion\n\n\n### Has this already been discussed elsewhere?\n\nI have already discussed this feature proposal on Discourse\n\n### Links to previous discussion of this feature:\n\nhttps://discuss.python.org/t/add-public-functions-to-inspect-dataclass-parameters-and-methods/108613/12","author":{"url":"https://github.com/DavidCEllis","@type":"Person","name":"DavidCEllis"},"datePublished":"2026-09-11T12:55:57Z","url":"https://github.com/python/cpython/issues/157314"}
| 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:5b7f57ae-52ed-b298-9924-8e9f493f4dfb |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 8444:17543D:61323C:7B28DE:6B020991 |
| html-safe-nonce | 082477cb2cd23dd066d74512442e74893923d1f4cf1f0355715f8ec01d3c6036 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4NDQ0OjE3NTQzRDo2MTMyM0M6N0IyOERFOjZCMDIwOTkxIiwidmlzaXRvcl9pZCI6IjEzMTcxNTkyODYyNzQ2NTY2NTciLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 6e07084eb922ba7ec4a4bfa7825fd54ca48a088967508bb8c3b49986bfd966f4 |
| hovercard-subject-tag | issue:5424547633 |
| 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/157314/issue_layout |
| twitter:image | https://opengraph.githubassets.com/1952ac72696da34246cb80b9064ab18a0ba400642daf2b82b4755c3bc152b740/python/cpython/issues/157314 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/1952ac72696da34246cb80b9064ab18a0ba400642daf2b82b4755c3bc152b740/python/cpython/issues/157314 |
| og:image:alt | Feature or enhancement Proposal: There are a few places both in the stdlib and in third party packages where tools attempt to discover specific features of how dataclasses are constructed. Currentl... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | DavidCEllis |
| 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