Title: gh-92041: Avoid repeated sys.modules scans in inspect.getmodule by mdeck · Pull Request #92042 · python/cpython · GitHub
Open Graph Title: gh-92041: Avoid repeated sys.modules scans in inspect.getmodule by mdeck · Pull Request #92042 · python/cpython
X Title: gh-92041: Avoid repeated sys.modules scans in inspect.getmodule by mdeck · Pull Request #92042 · python/cpython
Description: Summary This PR speeds up inspect.getmodule() for frame, traceback, and bare-code lookups without removing its filename-based fallback. A common affected flow is: inspect.stack() → frame/source resolution → inspect.getmodule(frame) On main, a filename-cache miss scans every value in sys.modules. This has appeared at application scale: Sentry reported inspect.stack() increasing from 4% to 54% of execution time in one worker type, and Home Assistant reported 7,184,347 ismodule() calls from this path during startup. Generated/private execution globals are used by libraries such as Jinja and attrs. Such frames can remain in the caller chain when logging, validation, or error reporting captures a stack. Design The implementation has two complementary paths. Registered frames and tracebacks For a frame or traceback, getmodule() reads f_globals["__name__"], looks that name up in sys.modules, requires module.__dict__ is f_globals, and verifies that the code and module origins match. A matching registered frame is resolved directly without scanning sys.modules. If ownership cannot be established, lookup continues through the existing filename-based path. This preserves unregistered execution globals, mismatched registered globals, ordinary files, and loader-backed sources such as zipimport. Bare code and filename fallback The filename map is cached while the canonical module registry remains unchanged. A private _imp query exposes a per-interpreter generation that is incremented when: the canonical sys.modules dictionary is mutated; a module's __file__, __name__, or __getattr__ metadata changes; or a module's class changes, which can make that metadata dynamic. Exact modules use the generation fast path. Module subclasses and modules whose metadata is supplied dynamically are recorded and revalidated individually, so one dynamic module does not disable caching for the rest of the registry. A replacement sys.modules mapping cannot be watched and is therefore scanned on each miss. Cache hits and rebuilt maps are validated against the mapping identity and generation; a scan that overlaps mutation is retried once and otherwise discarded. The cache is published as one tuple so concurrent and free-threaded readers cannot observe mismatched versions and maps. Compatibility and behavior The filename fallback and the reported zipimport/fresh-namespace getsource() behavior are preserved. Same-key module replacement and in-place changes to relevant module metadata invalidate the cache. Fileless modules and existing object fast paths retain their behavior. The longstanding modulesbyfile and _filesbymodname dictionary objects and their value shapes are preserved as compatibility mirrors. A registered frame's actual globals owner now wins if an unrelated module later reuses the same filename. This is intentional: globals identity establishes the executing module more precisely than a filename collision. No public API or import semantics are changed; the added _imp helper is private. Performance Measured against the PR's fixed main base (09b63170e3) using the same optimized interpreter and 10,002 sys.modules entries: Workload main PR Result Existing function fast path 0.221 µs 0.242 µs no material change Repeated registered frame 3.014 µs 0.872 µs 3.5× faster Cold registered frame 1.664 ms 1.248 µs 1,333× faster Repeated unregistered frame 1.469 ms 5.299 µs 277× faster Repeated mismatched-origin frame 742.8 µs 7.664 µs 97× faster Repeated bare-code miss 1.508 ms 5.243 µs 288× faster inspect.stack(), depth 2 905.1 µs 176.9 µs 5.1× faster inspect.stack(), depth 64 1.326 ms 580.4 µs 2.3× faster Cached filename fallback hit 2.928 µs 3.582 µs +0.654 µs Rebuilding after a relevant registry mutation remains O(number of modules) and is more expensive than the existing scan because the new cache records enough metadata to validate later lookups. Representative measurements put the break-even at roughly three stable misses per mutation. The optimization therefore targets stack/source inspection after imports and module metadata have settled, rather than workloads that mutate the registry between nearly every lookup. Verification The final tree was verified with: a 16-file release-build matrix covering 3,234 tests; a free-threaded matrix covering 945 tests; a pydebug reference-leak run covering 528 tests; targeted concurrent cache-publication, registry-mutation, dynamic-module, replacement-sys.modules, and subinterpreter tests; make -j4, make regen-all, and git diff --check. Coverage includes registered, unregistered, mismatched-origin, fileless, traceback, bare-code, zipimport, same-name replacement, metadata mutation, dynamic metadata, overlapping scans, cache publication, and module-lifetime cases. Issue: gh-92041
Open Graph Description: Summary This PR speeds up inspect.getmodule() for frame, traceback, and bare-code lookups without removing its filename-based fallback. A common affected flow is: inspect.stack() → frame/source res...
X Description: Summary This PR speeds up inspect.getmodule() for frame, traceback, and bare-code lookups without removing its filename-based fallback. A common affected flow is: inspect.stack() → frame/source res...
Opengraph URL: https://github.com/python/cpython/pull/92042
X: @github
Domain: github.com
IPv4 address: 140.82.112.4
| 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 | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:21c39bf4-788b-5d59-641f-924b1074ea34 |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | DBA2:249987:D3985B:11F6851:6B06505C |
| html-safe-nonce | 51e125a69f12d284b6cbb7a0c3123a9d12a28e2fb2ea79453bf674c9aa50f0ba |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEQkEyOjI0OTk4NzpEMzk4NUI6MTFGNjg1MTo2QjA2NTA1QyIsInZpc2l0b3JfaWQiOiIxNzQ0MzIxMjg0NTM3NzMzMjEyIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 4f060ddcf43a6deae13df261141cd91738670d38a678a55b15bbf1b6739b56ed |
| hovercard-subject-tag | pull_request:922730636 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,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/python/cpython/pull/92042/files |
| twitter:image | https://avatars.githubusercontent.com/u/1872833?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/1872833?s=400&v=4 |
| og:image:alt | Summary This PR speeds up inspect.getmodule() for frame, traceback, and bare-code lookups without removing its filename-based fallback. A common affected flow is: inspect.stack() → frame/source res... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | 772b6997ca4daa0428dd49a25d76052e765555ae560fe9c88517eb828bbd861e |
| turbo-cache-control | no-preview |
| diff-view | unified |
| 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 full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | f1f9a08f7c769a37f1dfc18ad43d463c222a7eea |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | no-cache |
Viewport: width=device-width