Cache sniffio availability instead of importing it on every call - #1132
Merged
Conversation
Merging this PR will not alter performance
Comparing Footnotes
|
`current_async_library()` re-imported `sniffio` on every invocation, falling back to "asyncio" on `ImportError`. Since anyio>=4.11 no longer depends on sniffio, anyone using `httpcore2[asyncio]` without trio installed pays a failed-import cost on every lock/event/semaphore setup, and Python doesn't cache failed imports. Now `sniffio` is imported once at module load, like `trio` and `anyio` already are, and `current_async_library()` just checks the cached reference. Only availability is cached, not the detected backend. Reported in encode/httpcore discussion pydantic#1102, with the fix and test strategy suggested in a follow-up comment: encode/httpcore#1102 (comment)
mbeijen
force-pushed
the
fix/sniffio-hot-path-import
branch
from
August 11, 2026 12:32
713688c to
03405e7
Compare
Kludex
approved these changes
Aug 13, 2026
Kludex
enabled auto-merge (squash)
August 13, 2026 12:34
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
current_async_library()re-importedsniffioon every invocation, falling back to "asyncio" onImportError. Since anyio>=4.11 no longer depends on sniffio, anyone usinghttpcore2[asyncio]without trio installed pays a failed-import cost on every lock/event/semaphore setup, and Python doesn't cache failed imports.Now
sniffiois imported once at module load, liketrioandanyioalready are, andcurrent_async_library()just checks the cached reference. Only availability is cached, not the detected backend.Reported in encode/httpcore discussion #1102, with the fix and test strategy suggested in a follow-up comment:
encode/httpcore#1102 (comment)
Summary
improve import time when modern anyio =->4.11 is installed and sniffio isn't
Checklist