René's URL Explorer Experiment


Title: Improve UX for mocking dataclasses that are problematic to instantiate · Issue #124176 · python/cpython · GitHub

Open Graph Title: Improve UX for mocking dataclasses that are problematic to instantiate · Issue #124176 · python/cpython

X Title: Improve UX for mocking dataclasses that are problematic to instantiate · Issue #124176 · python/cpython

Description: Feature or enhancement Proposal: Passing instance=True to create_autospec misses fields without default values, even when the given spec is a dataclass object: >>> from dataclasses import dataclass >>> @dataclass ... class Example: ... a...

Open Graph Description: Feature or enhancement Proposal: Passing instance=True to create_autospec misses fields without default values, even when the given spec is a dataclass object: >>> from dataclasses import dataclass...

X Description: Feature or enhancement Proposal: Passing instance=True to create_autospec misses fields without default values, even when the given spec is a dataclass object: >>> from dataclasses import ...

Opengraph URL: https://github.com/python/cpython/issues/124176

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Improve UX for mocking dataclasses that are problematic to instantiate","articleBody":"# Feature or enhancement\r\n\r\n### Proposal:\r\n\r\nPassing `instance=True` to `create_autospec` misses fields without default values, even when the given spec is a `dataclass` object:\r\n\r\n```python\r\n\u003e\u003e\u003e from dataclasses import dataclass\r\n\u003e\u003e\u003e @dataclass\r\n... class Example:\r\n...     a: int\r\n...     b: int = 0\r\n...     def sum_fields(self):\r\n...         return self.a + self.b\r\n...\r\n\u003e\u003e\u003e from unittest.mock import create_autospec\r\n\u003e\u003e\u003e mock_instance = create_autospec(Example(1))\r\n\u003e\u003e\u003e mock_instance_from_class = create_autospec(Example, instance=True)\r\n\u003e\u003e\u003e set(dir(mock_instance)) - set(dir(mock_instance_from_class))\r\n{'a'}\r\n```\r\n\r\nThis is despite dataclass definitions making their field information readily available for introspection on the class object (without requiring instantiation):\r\n\r\n```python\r\n\u003e\u003e\u003e from dataclasses import fields\r\n\u003e\u003e\u003e [(field.name, field.type) for field in fields(Example)]\r\n[('a', \u003cclass 'int'\u003e), ('b', \u003cclass 'int'\u003e)]\r\n```\r\n\r\nA similar problem occurs if the dataclass uses `__post_init__` to set attributes that are not otherwise set:\r\n\r\n```python\r\n\u003e\u003e\u003e from dataclasses import dataclass, field\r\n\u003e\u003e\u003e @dataclass\r\n... class PostInitExample:\r\n...     a: int = field(init=False)\r\n...     b: int = field(init=False)\r\n...     def __post_init__(self):\r\n...         self.a = self.b = 1\r\n...\r\n\u003e\u003e\u003e mock_post_init_class = create_autospec(Example)\r\n\u003e\u003e\u003e mock_post_init_class = create_autospec(PostInitExample)\r\n\u003e\u003e\u003e mock_post_init_instance = create_autospec(PostInitExample())\r\n\u003e\u003e\u003e set(dir(mock_post_init_instance)) - set(dir(mock_post_init_class()))\r\n{'b', 'a'}\r\n```\r\n\r\nWhile for most dataclasses it is straightforward to instantiate a specific instance and derive the mock autospec from that, this may not be desirable (or even feasible) if the dataclass requires references to real external resources to create a real instance.\r\n\r\nThere are various potential workarounds available for this functional gap, but they're all relatively clumsy, and come with their own problems (like not being able to use `spec_set=True` if the missing fields are added manually, or not handling defined methods properly if setting an explicit list of fields instead of using `autospec`, or still not adding the fields only defined in `__post_init__` if instantiating a class mock).\r\n\r\nBy contrast, if `create_autospec` were to be made explicitly aware of data classes, it could do a pass over `dataclasses.fields(spec)` and use the type information to fill in any missing fields that don't have class level default values set.\r\n\r\n### Has this already been discussed elsewhere?\r\n\r\nThis is a minor feature, which does not need previous discussion elsewhere\r\n\r\n### Links to previous discussion of this feature:\r\n\r\nPreviously filed here, but closed on the basis of `create_autospec` covering the use case: https://github.com/python/cpython/issues/80761\r\n\r\nThis is only true if the dataclass can be readily instantiated, hence this feature request.\r\n\r\nThere is also some previous discussion (and assorted attempted workarounds with various flaws) on this Stack Overflow question: https://stackoverflow.com/questions/51640505/how-to-use-spec-when-mocking-data-classes-in-python\n\n\u003c!-- gh-linked-prs --\u003e\n### Linked PRs\n* gh-124429\n* gh-124724\n\u003c!-- /gh-linked-prs --\u003e\n","author":{"url":"https://github.com/ncoghlan","@type":"Person","name":"ncoghlan"},"datePublished":"2024-09-17T14:41:16.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":6},"url":"https://github.com/124176/cpython/issues/124176"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:d1d3c872-d68b-1a4d-47fe-4cce37dce2b9
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idD70E:370C10:DE5339:130B986:6A55C4ED
html-safe-nonceb6e71d95b6b6ca7fe0fe95c61c71a3d673e82a9f73bb068116f22bd750fd40bf
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJENzBFOjM3MEMxMDpERTUzMzk6MTMwQjk4Njo2QTU1QzRFRCIsInZpc2l0b3JfaWQiOiI3Njk1MzI3NjQzNzIyNjk1OTE3IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0=
visitor-hmac923603d7dc72cbe525144bed76abbb4759e57be5318304c892e59ca044d837d1
hovercard-subject-tagissue:2531353865
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/124176/issue_layout
twitter:imagehttps://opengraph.githubassets.com/ed1a916da3a8aa36a625e7bdc0c41c5978dfc8d3715c99477a72cd0de9128adf/python/cpython/issues/124176
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/ed1a916da3a8aa36a625e7bdc0c41c5978dfc8d3715c99477a72cd0de9128adf/python/cpython/issues/124176
og:image:altFeature or enhancement Proposal: Passing instance=True to create_autospec misses fields without default values, even when the given spec is a dataclass object: >>> from dataclasses import dataclass...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamencoghlan
hostnamegithub.com
expected-hostnamegithub.com
Noneb5665c84831ed9ac4fb79519c16c9c5580ba8092fb8bb6e3e72972ec7197348e
turbo-cache-controlno-preview
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release8f8e1726192df8dce16872ceb503336c12e9ae78
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/cpython/issues/124176#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F124176
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F124176
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/issues/124176
Reloadhttps://github.com/python/cpython/issues/124176
Reloadhttps://github.com/python/cpython/issues/124176
Please reload this pagehttps://github.com/python/cpython/issues/124176
python https://github.com/python
cpythonhttps://github.com/python/cpython
Please reload this pagehttps://github.com/python/cpython/issues/124176
Notifications https://github.com/login?return_to=%2Fpython%2Fcpython
Fork 35k https://github.com/login?return_to=%2Fpython%2Fcpython
Star 73.8k https://github.com/login?return_to=%2Fpython%2Fcpython
Code https://github.com/python/cpython
Issues 5k+ https://github.com/python/cpython/issues
Pull requests 2.3k https://github.com/python/cpython/pulls
Actions https://github.com/python/cpython/actions
Projects https://github.com/python/cpython/projects
Security and quality 0 https://github.com/python/cpython/security
Insights https://github.com/python/cpython/pulse
Code https://github.com/python/cpython
Issues https://github.com/python/cpython/issues
Pull requests https://github.com/python/cpython/pulls
Actions https://github.com/python/cpython/actions
Projects https://github.com/python/cpython/projects
Security and quality https://github.com/python/cpython/security
Insights https://github.com/python/cpython/pulse
Improve UX for mocking dataclasses that are problematic to instantiatehttps://github.com/python/cpython/issues/124176#top
https://github.com/sobolevn
topic-dataclasseshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-dataclasses%22
type-featureA feature request or enhancementhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-feature%22
https://github.com/ncoghlan
ncoghlanhttps://github.com/ncoghlan
on Sep 17, 2024https://github.com/python/cpython/issues/124176#issue-2531353865
#80761https://github.com/python/cpython/issues/80761
https://stackoverflow.com/questions/51640505/how-to-use-spec-when-mocking-data-classes-in-pythonhttps://stackoverflow.com/questions/51640505/how-to-use-spec-when-mocking-data-classes-in-python
gh-124176: Add special support for dataclasses to create_autospec #124429https://github.com/python/cpython/pull/124429
gh-124176: create_autospec must not change how dataclass defaults are mocked #124724https://github.com/python/cpython/pull/124724
sobolevnhttps://github.com/sobolevn
topic-dataclasseshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-dataclasses%22
type-featureA feature request or enhancementhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-feature%22
Unittest & doctest issueshttps://github.com/orgs/python/projects/16
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.