Skip to content

perf: reduce root import overhead#1513

Open
wilyan09007 wants to merge 1 commit intoanthropics:mainfrom
wilyan09007:issue-1211-slow-imports
Open

perf: reduce root import overhead#1513
wilyan09007 wants to merge 1 commit intoanthropics:mainfrom
wilyan09007:issue-1211-slow-imports

Conversation

@wilyan09007
Copy link
Copy Markdown

@wilyan09007 wilyan09007 commented May 8, 2026

What

Lazily resolves heavy root re-exports from anthropic.__init__ so import anthropic no longer eagerly imports generated types, tools, Bedrock, Vertex, streaming, credentials, schema-transform modules, or the base Anthropic client stack.

The root package now defers _client, _types, _models, _base_client, _response, _constants, _exceptions, httpx, and pydantic until the corresponding exported attribute is first used. It also avoids importing anthropic.types from _exceptions.py at runtime just to satisfy the ErrorType annotation.

Why

Fixes #1211.

The issue reports slow root imports caused by eager type/client/tool imports. Deferring those modules keeps import anthropic lightweight while preserving anthropic.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 -q
  • uv run ruff check src\anthropic\__init__.py src\anthropic\_exceptions.py tests\test_imports.py
  • uv run ruff format --check src\anthropic\__init__.py src\anthropic\_exceptions.py tests\test_imports.py
  • uv run pyright src\anthropic\__init__.py src\anthropic\_exceptions.py tests\test_imports.py
  • git diff --check HEAD~1..HEAD
  • 10 subprocess timing runs for import anthropic: min 19.1ms, median 19.9ms, max 26.3ms
  • Import-state probe confirms import anthropic does not load httpx, pydantic, anthropic._client, or anthropic._types.

I also ran uv run pytest tests\test_client.py tests\test_response.py tests\test_legacy_response.py -q -n0; it reached 204 passed and failed on the existing Windows-local memory-leak sentinel and proxy-environment mount assertions, not on lazy import behavior.

@wilyan09007 wilyan09007 requested a review from a team as a code owner May 8, 2026 00:30
@wilyan09007 wilyan09007 force-pushed the issue-1211-slow-imports branch from fd2e46b to e8e2b6d Compare May 8, 2026 00:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Slow imports

1 participant