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
Domain: github.com
{"@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-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:c84476a9-dff8-23e9-7f03-8865551d183f |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9EAC:19B6A2:16899F4:1DCBB37:6B020279 |
| html-safe-nonce | 081fe04560f352a6dc50d637798bfe7e87e5c2fb489605b8253acb95f57fa053 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5RUFDOjE5QjZBMjoxNjg5OUY0OjFEQ0JCMzc6NkIwMjAyNzkiLCJ2aXNpdG9yX2lkIjoiNTk4MTQzOTE0NjMzNjU4NDMxNCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 863ccca23f64650186357e7d506fb411d829dd019510ab97aad1d6623d33326c |
| hovercard-subject-tag | issue:5891362782 |
| 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/159580/issue_layout |
| twitter:image | https://opengraph.githubassets.com/c4a1d73dc46c8156375a71a56c4512d759685ef44c0feb52cf386540b5c8d90a/python/cpython/issues/159580 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/c4a1d73dc46c8156375a71a56c4512d759685ef44c0feb52cf386540b5c8d90a/python/cpython/issues/159580 |
| og:image:alt | 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... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | eendebakpt |
| 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