René's URL Explorer Experiment


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

direct link

Domain: github.com

IPv4 address: 140.82.112.4

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/:user_id/:repository/pull/:id/files(.:format)
route-controllerpull_requests
route-actionfiles
fetch-noncev2:21c39bf4-788b-5d59-641f-924b1074ea34
current-catalog-service-hashae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b
request-idDBA2:249987:D3985B:11F6851:6B06505C
html-safe-nonce51e125a69f12d284b6cbb7a0c3123a9d12a28e2fb2ea79453bf674c9aa50f0ba
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEQkEyOjI0OTk4NzpEMzk4NUI6MTFGNjg1MTo2QjA2NTA1QyIsInZpc2l0b3JfaWQiOiIxNzQ0MzIxMjg0NTM3NzMzMjEyIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0=
visitor-hmac4f060ddcf43a6deae13df261141cd91738670d38a678a55b15bbf1b6739b56ed
hovercard-subject-tagpull_request:922730636
github-keyboard-shortcutsrepository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///pull_requests/show/files
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/python/cpython/pull/92042/files
twitter:imagehttps://avatars.githubusercontent.com/u/1872833?s=400&v=4
twitter:cardsummary_large_image
og:imagehttps://avatars.githubusercontent.com/u/1872833?s=400&v=4
og:image:altSummary 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_nameGitHub
og:typeobject
hostnamegithub.com
expected-hostnamegithub.com
None772b6997ca4daa0428dd49a25d76052e765555ae560fe9c88517eb828bbd861e
turbo-cache-controlno-preview
diff-viewunified
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 full-width
disable-turbotrue
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
releasef1f9a08f7c769a37f1dfc18ad43d463c222a7eea
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/cpython/pull/92042/files#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fpull%2F92042%2Ffiles
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%2Fpull%2F92042%2Ffiles
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fpull_requests%2Fshow%2Ffiles&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/pull/92042/files
Reloadhttps://github.com/python/cpython/pull/92042/files
Reloadhttps://github.com/python/cpython/pull/92042/files
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
Sign up for GitHub https://github.com/signup?return_to=%2Fpython%2Fcpython%2Fissues%2Fnew%2Fchoose
terms of servicehttps://docs.github.com/terms
privacy statementhttps://docs.github.com/privacy
Sign inhttps://github.com/login?return_to=%2Fpython%2Fcpython%2Fissues%2Fnew%2Fchoose
mdeckhttps://github.com/mdeck
python:mainhttps://github.com/python/cpython/tree/main
mdeck:fix_inspecthttps://github.com/mdeck/cpython/tree/fix_inspect
Conversation 36 https://github.com/python/cpython/pull/92042
Commits 6 https://github.com/python/cpython/pull/92042/commits
Checks 59 https://github.com/python/cpython/pull/92042/checks
Files changed https://github.com/python/cpython/pull/92042/files
Please reload this pagehttps://github.com/python/cpython/pull/92042/files
gh-92041: Avoid repeated sys.modules scans in inspect.getmodule https://github.com/python/cpython/pull/92042/files#top
Show all changes 6 commits https://github.com/python/cpython/pull/92042/files
909b828 gh-92041: Resolve frame modules from globals mdeck Aug 14, 2026 https://github.com/python/cpython/pull/92042/commits/909b8280ee97af712701645ba72d9a02a713fdaa
2bcf546 Fix NEWS entry filename mdeck Aug 14, 2026 https://github.com/python/cpython/pull/92042/commits/2bcf546f0557ef0fb33b2f1bdfed4a038fb61695
58703a5 gh-92041: Address getmodule review findings mdeck Aug 14, 2026 https://github.com/python/cpython/pull/92042/commits/58703a5c2859db32ba2d6397a6c8c20a5ab08534
3fbfadc gh-92041: Preserve frame filename semantics mdeck Aug 14, 2026 https://github.com/python/cpython/pull/92042/commits/3fbfadc521f0d8611c542ee2f20b4b94f4657e87
0afefeb gh-92041: Preserve getmodule filename fallback mdeck Aug 24, 2026 https://github.com/python/cpython/pull/92042/commits/0afefebe997bb9ddfc51ce72d4d28affe3fa68cd
33ccc7b gh-92041: Safely cache inspect.getmodule filename lookups mdeck Aug 26, 2026 https://github.com/python/cpython/pull/92042/commits/33ccc7b47429caaa33e4bf7797b84cc7ceb50903
Clear filters https://github.com/python/cpython/pull/92042/files
Please reload this pagehttps://github.com/python/cpython/pull/92042/files
Please reload this pagehttps://github.com/python/cpython/pull/92042/files
pycore_interp_structs.h https://github.com/python/cpython/pull/92042/files#diff-6075b6142803c1eccc213aa150704fd639443c65311d5999f69a5ea77cb76756
inspect.py https://github.com/python/cpython/pull/92042/files#diff-b89cd06e4637abacb73f2500301ff979a67ad7ecbfa7cf151c7243715898d7ea
utils.py https://github.com/python/cpython/pull/92042/files#diff-8e9a29443bf1ce629c10cc3b9e8cd9c3db85e3db313859d0a645f7736a845491
__init__.py https://github.com/python/cpython/pull/92042/files#diff-ea25b7196846cae64e3ed2b3fb2e1ee420961442fcd801a07bcd9000178bbd58
test_inspect.py https://github.com/python/cpython/pull/92042/files#diff-92d8ecc68ed9e7ce3b31a764d5b0368db1514365c2a6433bbe3bad5c3210cea0
test_zipimport_support.py https://github.com/python/cpython/pull/92042/files#diff-40725dfe25e507217ceaebaefc65bbc1da7998077aaf5b0ccb35d8aed44594d1
2026-08-14-16-30-00.gh-issue-92041.kD7pQm.rst https://github.com/python/cpython/pull/92042/files#diff-1498350f949804773af8e85268e963f434cbec6b532861dfd7803cbe098eeddd
moduleobject.c https://github.com/python/cpython/pull/92042/files#diff-8c2a0fd137780a0ee11c19aae8e46e8490f7667698cd78a5bde466bc995a08c5
import.c.h https://github.com/python/cpython/pull/92042/files#diff-5d1c1dd3ea561082c4a09d0e3ead6f3ea57f24d0fe06e2d719bed95e6324eee9
import.c https://github.com/python/cpython/pull/92042/files#diff-28cfc3e2868980a79d93d2ebdc8747dcb9231f3dd7f2caef96e74107d1ea3bf3
Include/internal/pycore_interp_structs.hhttps://github.com/python/cpython/pull/92042/files#diff-6075b6142803c1eccc213aa150704fd639443c65311d5999f69a5ea77cb76756
View file https://github.com/mdeck/cpython/blob/33ccc7b47429caaa33e4bf7797b84cc7ceb50903/Include/internal/pycore_interp_structs.h
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/92042/{{ revealButtonHref }}
https://github.com/python/cpython/pull/92042/files#diff-6075b6142803c1eccc213aa150704fd639443c65311d5999f69a5ea77cb76756
https://github.com/python/cpython/pull/92042/files#diff-6075b6142803c1eccc213aa150704fd639443c65311d5999f69a5ea77cb76756
Lib/inspect.pyhttps://github.com/python/cpython/pull/92042/files#diff-b89cd06e4637abacb73f2500301ff979a67ad7ecbfa7cf151c7243715898d7ea
View file https://github.com/mdeck/cpython/blob/33ccc7b47429caaa33e4bf7797b84cc7ceb50903/Lib/inspect.py
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/92042/{{ revealButtonHref }}
https://github.com/python/cpython/pull/92042/files#diff-b89cd06e4637abacb73f2500301ff979a67ad7ecbfa7cf151c7243715898d7ea
https://github.com/python/cpython/pull/92042/files#diff-b89cd06e4637abacb73f2500301ff979a67ad7ecbfa7cf151c7243715898d7ea
https://github.com/python/cpython/pull/92042/files#diff-b89cd06e4637abacb73f2500301ff979a67ad7ecbfa7cf151c7243715898d7ea
sprajshttps://github.com/sprajs
Sep 19, 2026https://github.com/python/cpython/pull/92042/files#r4051803914
Learn morehttps://docs.github.com/articles/managing-disruptive-comments/#hiding-a-comment
Please reload this pagehttps://github.com/python/cpython/pull/92042/files
https://github.com/python/cpython/pull/92042/files#diff-b89cd06e4637abacb73f2500301ff979a67ad7ecbfa7cf151c7243715898d7ea
Lib/test/libregrtest/utils.pyhttps://github.com/python/cpython/pull/92042/files#diff-8e9a29443bf1ce629c10cc3b9e8cd9c3db85e3db313859d0a645f7736a845491
View file https://github.com/mdeck/cpython/blob/33ccc7b47429caaa33e4bf7797b84cc7ceb50903/Lib/test/libregrtest/utils.py
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/92042/{{ revealButtonHref }}
https://github.com/python/cpython/pull/92042/files#diff-8e9a29443bf1ce629c10cc3b9e8cd9c3db85e3db313859d0a645f7736a845491
https://github.com/python/cpython/pull/92042/files#diff-8e9a29443bf1ce629c10cc3b9e8cd9c3db85e3db313859d0a645f7736a845491
Please reload this pagehttps://github.com/python/cpython/pull/92042/files
Please reload this pagehttps://github.com/python/cpython/pull/92042/files
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

Response headers:
Servergithub.com
Content-Typetext/html; charset=utf-8
Cache-Controlno-cache

Viewport: width=device-width


URLs of crawlers that visited me.