perf: reduce root import overhead#1513
Open
wilyan09007 wants to merge 1 commit intoanthropics:mainfrom
Open
Conversation
fd2e46b to
e8e2b6d
Compare
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.
What
Lazily resolves heavy root re-exports from
anthropic.__init__soimport anthropicno longer eagerly imports generatedtypes, tools, Bedrock, Vertex, streaming, credentials, schema-transform modules, or the baseAnthropicclient stack.The root package now defers
_client,_types,_models,_base_client,_response,_constants,_exceptions,httpx, andpydanticuntil the corresponding exported attribute is first used. It also avoids importinganthropic.typesfrom_exceptions.pyat runtime just to satisfy theErrorTypeannotation.Why
Fixes #1211.
The issue reports slow root imports caused by eager type/client/tool imports. Deferring those modules keeps
import anthropiclightweight while preservinganthropic.Anthropic,from anthropic import Anthropic, and the existing root re-export surface.Verification / How to test
uv run pytest tests\test_imports.py tests\lib\test_vertex.py tests\lib\tools\test_functions.py -quv run ruff check src\anthropic\__init__.py src\anthropic\_exceptions.py tests\test_imports.pyuv run ruff format --check src\anthropic\__init__.py src\anthropic\_exceptions.py tests\test_imports.pyuv run pyright src\anthropic\__init__.py src\anthropic\_exceptions.py tests\test_imports.pygit diff --check HEAD~1..HEADimport anthropic: min19.1ms, median19.9ms, max26.3msimport anthropicdoes not loadhttpx,pydantic,anthropic._client, oranthropic._types.I also ran
uv run pytest tests\test_client.py tests\test_response.py tests\test_legacy_response.py -q -n0; it reached204 passedand failed on the existing Windows-local memory-leak sentinel and proxy-environment mount assertions, not on lazy import behavior.