René's URL Explorer Experiment


Title: Improve performance of isinstance() for misses and improve documentation · Issue #159580 · python/cpython · GitHub

Open Graph Title: Improve performance of isinstance() for misses and improve documentation · Issue #159580 · python/cpython

X Title: Improve performance of isinstance() for misses and improve documentation · Issue #159580 · python/cpython

Description: Feature or enhancement When isinstance(obj, cls) fails the PyObject_TypeCheck() test, object_isinstance() looks up obj.__class__ through the full attribute machinery to handle proxies that override __class__. For ordinary objects that lo...

Open Graph Description: Feature or enhancement When isinstance(obj, cls) fails the PyObject_TypeCheck() test, object_isinstance() looks up obj.__class__ through the full attribute machinery to handle proxies that override...

X Description: Feature or enhancement When isinstance(obj, cls) fails the PyObject_TypeCheck() test, object_isinstance() looks up obj.__class__ through the full attribute machinery to handle proxies that override...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Improve performance of isinstance() for misses and improve documentation","articleBody":"### Feature or enhancement\n\nWhen `isinstance(obj, cls)` fails the `PyObject_TypeCheck()` test, `object_isinstance()` looks up `obj.__class__` through the full attribute machinery to handle proxies that override `__class__`. For ordinary objects that lookup resolves to `object`'s own `__class__` getset descriptor, so it calls the getset, type-checks, increfs the type, compares it to `Py_TYPE(obj)` and decrefs it again, all to confirm what was already known.\n\nThis PR checks whether `__class__` resolves to `object`'s getset descriptor for a type that uses generic attribute lookup. If so the answer is `False` without any call.  Every `isinstance()` call that returns `False` with an exact `type` as the second argument benefits, including each non-matching entry of a tuple of types, which is the common `isinstance(o, (str, int, float, ...))` dispatch pattern. \n\nThe `isinstance()` documentation now states that a `__class__` attribute differing from `type(object)` is also consulted, which was undocumented.\n\n## Benchmarks\n\nRunning `isinstance(point, Other)` with `point` a dataclass\n\n| case | main | PR | speedup | p10..p90 |\n|---|---:|---:|---:|---|\n| ctl: `a + b` (ints) | 49.7 ns | 49.2 ns | 1.00x | 0.94..1.08 |\n| ctl: `s1 + s2` (str) | 67.6 ns | 67.7 ns | 1.00x | 0.96..1.08 |\n| `isinstance(1, int)` (exact hit) | 55.5 ns | 55.2 ns | 1.00x | 0.95..1.10 |\n| `isinstance(1, str)` (False) | 74.1 ns | 64.0 ns | **1.15x** | 1.09..1.26 |\n| `isinstance(obj, Other)` (False) | 69.7 ns | 59.6 ns | **1.16x** | 1.09..1.26 |\n| `isinstance(1, (str, bytes, float))` (3 misses) | 164.8 ns | 135.3 ns | **1.22x** | 1.13..1.32 |\n| `isinstance(1, (str, int))` (miss, hit) | 109.5 ns | 100.1 ns | **1.11x** | 1.05..1.17 |\n\nOn the free-threaded build the gain is larger under contention. On main the `__class__` lookup returns a new reference to the instance's type, so when the instance is of a heap type (any Python class) every thread does an atomic incref/decref on the shared type object. The fast path takes no reference. \n\n| threads | main | PR | main / PR |\n|---:|---:|---:|---:|\n| 1 | 7.1 ms | 6.3 ms | 1.12x |\n| 2 | 8.6 ms | 6.9 ms | 1.25x |\n| 4 | 22.3 ms | 7.4 ms | 3.01x |\n| 8 | 56.3 ms | 12.3 ms | 4.57x |\n\n`dataclasses.is_dataclass(point)`, whose first step is a failing `isinstance(obj, type)`:\n\n| threads | main | PR | main / PR |\n|---:|---:|---:|---:|\n| 1 | 19.6 ms | 16.7 ms | 1.18x |\n| 2 | 24.0 ms | 21.4 ms | 1.12x |\n| 4 | 40.7 ms | 37.5 ms | 1.08x |\n| 8 | 83.0 ms | 75.2 ms | 1.10x |\n\n\n\u003cdetails>\u003csummary>Benchmark scripts\u003c/summary>\n\nContended runs (free-threaded build):\n\n```python\nimport time, threading, dataclasses\n\n@dataclasses.dataclass\nclass Point:\n    x: int\n    y: int\n\nclass Other:\n    pass\n\nis_dataclass = dataclasses.is_dataclass\nWORK = 100_000\n\ndef case_micro():\n    pt = Point(1, 2)          # per-thread instance; the shared object is the type\n    for _ in range(WORK):\n        isinstance(pt, Other)\n\ndef case_is_dataclass():\n    pt = Point(1, 2)\n    for _ in range(WORK):\n        is_dataclass(pt)\n\ndef run(fn, nthreads):\n    ts = [threading.Thread(target=fn) for _ in range(nthreads)]\n    t0 = time.perf_counter()\n    for t in ts: t.start()\n    for t in ts: t.join()\n    return time.perf_counter() - t0\n\nfor name, fn in ((\"isinstance(dc, Other)\", case_micro), (\"is_dataclass(dc)\", case_is_dataclass)):\n    for n in (1, 2, 4, 8):\n        print(name, n, f\"{min(run(fn, n) for _ in range(3)) * 1e3:.1f} ms\")\n```\n\nSingle-threaded table:\n\n```python\nimport pyperf\n\nrunner = pyperf.Runner()\nrunner.timeit(\"isinstance(1, int)  (exact hit, control)\", \"isinstance(x, int)\", setup=\"x = 1\")\nrunner.timeit(\"isinstance(1, str)  (False)\", \"isinstance(x, str)\", setup=\"x = 1\")\nrunner.timeit(\"isinstance(obj, Other)  (False)\", \"isinstance(c, D)\",\n              setup=\"C = type('C', (), {}); D = type('D', (), {}); c = C()\")\nrunner.timeit(\"isinstance(1, (str, bytes, float))  (3 misses)\", \"isinstance(x, (str, bytes, float))\", setup=\"x = 1\")\nrunner.timeit(\"isinstance(1, (str, int))  (miss, hit)\", \"isinstance(x, (str, int))\", setup=\"x = 1\")\n```\n\n\u003c/details>\n\n\n### Has this already been discussed elsewhere?\n\nNo discussion on the optimization, but the behavior of ininstance has been discussed a lot:\n\n\n- gh-76864: proposal to bypass `__getattribute__` for the `__class__` lookup; rejected, overridden `__getattribute__` must stay honoured (this PR keeps it).\n- gh-79264, gh-144873: the exact-type shortcut skips `__instancecheck__` by design; doc PR gh-144997.\n- gh-153772 / gh-154149: abc `isinstance` falls back to `type(obj)` when `__class__` is unavailable, matching the built-in.\n- gh-139103, gh-157526: free-threading scaling reports with the same refcount-contention cause.\n- [Documenting isinstance behavior with faked `__class__`](https://discuss.python.org/t/documenting-isinstance-behavior-with-faked-class/107532) (Discourse, 2026): the doc change in this PR covers that request.\n\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-159581\n* gh-160424\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/eendebakpt","@type":"Person","name":"eendebakpt"},"datePublished":"2026-10-16T21:21:00Z","url":"https://github.com/python/cpython/issues/159580"}

react-profiling0
react-import-mapreact,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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:c84476a9-dff8-23e9-7f03-8865551d183f
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id9EAC:19B6A2:16899F4:1DCBB37:6B020279
html-safe-nonce081fe04560f352a6dc50d637798bfe7e87e5c2fb489605b8253acb95f57fa053
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5RUFDOjE5QjZBMjoxNjg5OUY0OjFEQ0JCMzc6NkIwMjAyNzkiLCJ2aXNpdG9yX2lkIjoiNTk4MTQzOTE0NjMzNjU4NDMxNCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac863ccca23f64650186357e7d506fb411d829dd019510ab97aad1d6623d33326c
hovercard-subject-tagissue:5891362782
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/159580/issue_layout
twitter:imagehttps://opengraph.githubassets.com/c4a1d73dc46c8156375a71a56c4512d759685ef44c0feb52cf386540b5c8d90a/python/cpython/issues/159580
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/c4a1d73dc46c8156375a71a56c4512d759685ef44c0feb52cf386540b5c8d90a/python/cpython/issues/159580
og:image:altFeature or enhancement When isinstance(obj, cls) fails the PyObject_TypeCheck() test, object_isinstance() looks up obj.__class__ through the full attribute machinery to handle proxies that override...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameeendebakpt
hostnamegithub.com
expected-hostnamegithub.com
None87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456
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
release423dbb54c5e7bfecc838eb387c1435eb3d0e760d
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/cpython/issues/159580#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F159580
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
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
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://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
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F159580
Sign uphttps://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/159580
Reloadhttps://github.com/python/cpython/issues/159580
Reloadhttps://github.com/python/cpython/issues/159580
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
https://github.com/python/cpython
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/159580
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/159580
Improve performance of isinstance() for misses and improve documentationhttps://github.com/python/cpython/issues/159580#top
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
performancePerformance or resource usagehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22performance%22
type-featureA feature request or enhancementhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-feature%22
https://github.com/eendebakpt
eendebakpthttps://github.com/eendebakpt
on Oct 16, 2026https://github.com/python/cpython/issues/159580#issue-5891362782
isinstance is calling ob.__getattribute__ as a fallback instead of object.__class__.__get__ #76864https://github.com/python/cpython/issues/76864
Fix documentation for __instancecheck__ #79264https://github.com/python/cpython/issues/79264
Overzealous Optimization For isinstance #144873https://github.com/python/cpython/issues/144873
gh-144873: Document isinstance Edge Case #144997https://github.com/python/cpython/pull/144997
isinstance check against collection.abc classes fails if value has no __class__ #153772https://github.com/python/cpython/issues/153772
gh-153772: Make abc isinstance() tolerate instances without __class__ #154149https://github.com/python/cpython/pull/154149
Poor thread scaling when constructing instances or accessing attributes #139103https://github.com/python/cpython/issues/139103
Free-threading scalability issue in ABC isinstance checking #157526https://github.com/python/cpython/issues/157526
Documenting isinstance behavior with faked __class__https://discuss.python.org/t/documenting-isinstance-behavior-with-faked-class/107532
gh-159580: Improve performance of isinstance() for misses and improve documentation #159581https://github.com/python/cpython/pull/159581
gh-159580: use _Py_INCREF_TYPE in object.__class__ #160424https://github.com/python/cpython/pull/160424
eendebakpthttps://github.com/eendebakpt
type-featureA feature request or enhancementhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-feature%22
on Oct 16, 2026https://github.com/python/cpython/issues/159580#event-33484538571
picnixzhttps://github.com/picnixz
performancePerformance or resource usagehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22performance%22
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
on Oct 16, 2026https://github.com/python/cpython/issues/159580#event-33485295667
kevinprimeraquecreo-stackhttps://github.com/kevinprimeraquecreo-stack
Project_VKhttps://github.com/users/kevinprimeraquecreo-stack/projects/1
Project_VKhttps://github.com/users/kevinprimeraquecreo-stack/projects/1
on Oct 18, 2026https://github.com/python/cpython/issues/159580#event-33592183906
github-project-automationhttps://github.com/apps/github-project-automation
Project_VKhttps://github.com/users/kevinprimeraquecreo-stack/projects/1
on Oct 18, 2026https://github.com/python/cpython/issues/159580
kumaraditya303https://github.com/kumaraditya303
on Oct 23, 2026https://github.com/python/cpython/issues/159580#event-34032982877
gh-159580: use _Py_INCREF_TYPE in object.__class__ (#160424)https://github.com/python/cpython/commit/b1e32ff4f33d93d2b876ff83da3b578e7829c8d4
gh-159580https://github.com/python/cpython/issues/159580
#160424https://github.com/python/cpython/pull/160424
b1e32ffhttps://github.com/python/cpython/commit/b1e32ff4f33d93d2b876ff83da3b578e7829c8d4
kumaraditya303https://github.com/kumaraditya303
on Nov 20, 2026https://github.com/python/cpython/issues/159580#event-36760347623
gh-159580: Improve performance of isinstance() for misses and improve…https://github.com/python/cpython/commit/8dbf4cfc14482f44954bf296f861f3aaec4eb968
gh-159580https://github.com/python/cpython/issues/159580
8dbf4cfhttps://github.com/python/cpython/commit/8dbf4cfc14482f44954bf296f861f3aaec4eb968
kumaraditya303https://github.com/kumaraditya303
completedhttps://github.com/python/cpython/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on Nov 20, 2026https://github.com/python/cpython/issues/159580#event-36760350659
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/159580
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/159580
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
performancePerformance or resource usagehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22performance%22
type-featureA feature request or enhancementhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-feature%22
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.