Import Anthropic
What Importing Does
Installing the SDK (Lesson 4) puts the anthropic package on your computer. Importing it makes that code available inside a specific Python program.
import anthropic
When Python runs this line, it:
- Searches for a module named
anthropicin the folders listed insys.path. These are the script's own folder, the standard library, and thesite-packagesfolder of the active environment. - Runs the package's initialization code the first time it is imported. This defines the client classes, exceptions, and types.
- Caches the module in
sys.modules. Later imports anywhere in the same program reuse it instead of loading it again. - Binds a name in your file, here
anthropic, so your code can use the module.
Understanding these four steps explains most import errors, which are covered later in this lesson.
Package, Module, and Names
A few terms are used precisely in this lesson:
| Term | Meaning | Example |
|---|---|---|
| Package | A folder of Python modules that can be imported | anthropic |
| Module | A single importable unit of Python code | anthropic, anthropic.types |
| Subpackage | A package inside a package | anthropic.types |
| Name | Anything defined inside a module: a class, function, or constant | Anthropic, AuthenticationError |
The SDK's main names live at the top level of the package. Data types live in the anthropic.types subpackage.
Three Ways to Import
1. Import the Module
import anthropic
client = anthropic.Anthropic()
try:
...
except anthropic.AuthenticationError:
...
Everything is accessed with the anthropic. prefix.
- Advantage: it is always obvious where a name comes from.
anthropic.RateLimitErrorcannot be confused with a rate-limit error from another library. - Disadvantage: the code is slightly longer.
2. Import Specific Names
from anthropic import Anthropic, AuthenticationError, RateLimitError
client = Anthropic()
try:
...
except AuthenticationError:
...
- Advantage: short and readable. The import line also documents exactly which parts of the SDK the file uses.
- Disadvantage: in a file that uses several libraries, generic names such as
RateLimitErrororAPIErrorcan clash or become ambiguous.
3. Combine Both
import anthropic
from anthropic import Anthropic
client = Anthropic()
try:
...
except anthropic.APIStatusError as error:
...
This is the style used in most of this tutorial. The client class is imported directly because it is used often. Exceptions keep the anthropic. prefix, which makes error-handling code self-explanatory.
| Style | Example | Best for |
|---|---|---|
import anthropic | anthropic.Anthropic() | Files that use many SDK names, or that also use other API libraries |
from anthropic import X | Anthropic() | Small scripts and files that use a few names often |
| Combined | Anthropic() + anthropic.RateLimitError | Most application code |
Avoid import *
from anthropic import * # Avoid
This imports every public name into your file. It hides where names come from, can silently overwrite your own names, and confuses editors and linters. Python's style guide, PEP 8, recommends against wildcard imports.
Aliases
You can rename an import with as:
import anthropic as ant
This works, but it makes code harder for others to read, because anthropic is short enough already. Use aliases only to resolve a real name conflict.
What You Can Import
Clients
| Name | Purpose | Lessons |
|---|---|---|
Anthropic | Synchronous client for the Claude API | Most lessons |
AsyncAnthropic | Asynchronous client | 71–80 |
AnthropicBedrockMantle, AnthropicBedrock | Amazon Bedrock | 161 |
AnthropicVertex | Claude Models on Google Cloud (Google managed) | 162 |
AnthropicGoogleCloud | Claude Models on Google Cloud (Anthropic managed) | 162 |
AnthropicAWS | Claude Platform on AWS | 161 |
AnthropicFoundry | Microsoft Foundry | 163 |
All of these classes are included in the base package. Most cloud clients also need the matching extra installed, such as pip install "anthropic[bedrock]", before they can be used.
Exceptions
from anthropic import (
AnthropicError, # Base class of all SDK errors
APIError, # Base class of API-related errors
APIConnectionError, # Could not reach the API
APITimeoutError, # The request timed out
APIStatusError, # The API returned an error status code
BadRequestError, # 400
AuthenticationError, # 401
PermissionDeniedError, # 403
NotFoundError, # 404
ConflictError, # 409
UnprocessableEntityError, # 422
RateLimitError, # 429
InternalServerError, # 500 and above
)
These form a hierarchy, so catching a parent also catches its children:
AnthropicError
└── APIError
├── APIConnectionError
│ └── APITimeoutError
└── APIStatusError
├── BadRequestError (400)
├── AuthenticationError (401)
├── PermissionDeniedError (403)
├── NotFoundError (404)
├── ConflictError (409)
├── UnprocessableEntityError (422)
├── RateLimitError (429)
└── InternalServerError (≥500)
Lessons 141–150 use this hierarchy to build reliable error handling.
HTTP and Tool Helpers
| Name | Purpose |
|---|---|
DefaultHttpxClient | Customize the sync client's HTTP layer, for example with a proxy, while keeping SDK defaults |
DefaultAsyncHttpxClient | The same for the async client |
DefaultAioHttpClient | The aiohttp backend for the async client (needs the aiohttp extra) |
beta_tool | Decorator that turns a Python function into a tool definition (Lesson 91) |
Types
The anthropic.types subpackage contains the classes that describe requests and responses:
from anthropic.types import Message, MessageParam, TextBlock
| Type | What it describes |
|---|---|
Message | A complete response from client.messages.create() |
TextBlock | A text content block inside message.content |
MessageParam | One message in the messages list you send. Since SDK 2.0.0 it is a union of UserMessageParam, AssistantMessageParam, and SystemMessageParam. |
You rarely need to construct these yourself: responses arrive already typed, and requests can be plain dictionaries. Their main use is in type hints, which let editors and type checkers catch mistakes:
from anthropic import Anthropic
from anthropic.types import Message, MessageParam
def ask(client: Anthropic, history: list[MessageParam]) -> Message:
return client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=history,
)
The annotations say precisely what the function accepts and returns. If you pass the wrong kind of value, your editor can warn you before you run the code.
Note: In SDK 2.x, use dictionaries for messages (
{"role": "user", "content": "Hi"}) andMessageParamonly as an annotation. CallingMessageParam(...)like a constructor raisesTypeError(Lesson 5).
The Version
import anthropic
print(anthropic.__version__)
__version__ is a module-level string containing the installed SDK version. It is useful in startup logs and bug reports.
Exploring the SDK from Python
You can discover what the SDK offers without leaving Python.
List Public Names
import anthropic
public_names = [name for name in dir(anthropic) if not name.startswith("_")]
print(public_names)
dir() lists every name defined in the module. Filtering out names that start with _ leaves the public ones.
Read Built-in Documentation
import anthropic
help(anthropic.Anthropic)
help() displays the class's docstring and methods. In an editor such as VS Code or PyCharm, hovering over a name or pressing Go to Definition shows the same information and lets you browse the SDK's source code. The source code is fully type-annotated, so it reads almost like documentation.
Check the Exception Hierarchy
import anthropic
print(anthropic.RateLimitError.__mro__)
__mro__ (method resolution order) lists a class and all of its parent classes, in order. It confirms that RateLimitError is a kind of APIStatusError, which is a kind of APIError, and so on.
Where to Put Imports
PEP 8 recommends placing imports at the top of the file, grouped in this order with a blank line between groups:
# 1. Standard library
import os
import sys
from pathlib import Path
# 2. Third-party packages
import anthropic
from anthropic import Anthropic
from dotenv import load_dotenv
# 3. Your own project's modules
from config import settings
Why this order: it shows at a glance which dependencies a file has, and which of them must be installed (group 2) or provided by your own project (group 3). Tools such as isort and ruff can sort imports automatically.
Practical Example: A Shared Claude Module
In a real project, one module typically owns the SDK setup, and other modules import from it. This keeps SDK imports and configuration in one place.
Project Structure
claude-app/
├── claude_service.py # The only module that creates the client
├── summarize.py # Uses claude_service
└── classify.py # Uses claude_service
claude_service.py
"""claude_service.py: a single place for Anthropic SDK setup."""
import anthropic
from anthropic import Anthropic
from anthropic.types import Message
MODEL = "claude-opus-5-5"
client = Anthropic()
class ClaudeServiceError(Exception):
"""Raised when a request to Claude fails."""
def extract_text(message: Message) -> str:
"""Join the text of every text block in a response."""
return "".join(block.text for block in message.content if block.type == "text")
def ask(prompt: str, max_tokens: int = 1024) -> str:
try:
message = client.messages.create(
model=MODEL,
max_tokens=max_tokens,
messages=[{"role": "user", "content": prompt}],
)
except anthropic.APIError as error:
raise ClaudeServiceError(f"Claude request failed: {error}") from error
return extract_text(message)
summarize.py
"""summarize.py: uses the shared service, with no direct SDK imports."""
from claude_service import ClaudeServiceError, ask
text = (
"Python virtual environments isolate project dependencies so that "
"different projects can use different package versions safely."
)
try:
print(ask(f"Summarize in one short sentence:\n\n{text}"))
except ClaudeServiceError as error:
print(f"Could not summarize: {error}")
How It Works
- Only
claude_service.pyimportsanthropic. Other modules importaskandClaudeServiceError. If the SDK changes in a future major version, there is one file to update. - The client is created once, when
claude_serviceis first imported. Thanks to Python's module cache (sys.modules), every other module that importsclaude_serviceshares the same client object. extract_text()joins the text blocks instead of readingmessage.content[0]. A response can begin with a non-text block, such as a thinking block on models that think before answering (Lessons 11 and 16).except anthropic.APIErrorcatches every API-related failure: connection problems, timeouts, and error status codes. It re-raises it as the application's ownClaudeServiceError, so callers do not need to know about SDK exceptions.from errorkeeps the original exception attached for debugging.
Common Mistakes
ModuleNotFoundError: No module named 'anthropic'
Why: the package is not installed in the interpreter that runs the code. Usually the virtual environment is not activated, or the editor or notebook uses a different interpreter.
Fix:
python -c "import sys; print(sys.executable)"
python -m pip show anthropic
The interpreter path and the package's Location must belong to the same environment. Install with python -m pip install anthropic if needed (Lesson 4).
ImportError: cannot import name 'Anthropic' from partially initialized module 'anthropic'
Why: a file in your project is named anthropic.py, or a folder is named anthropic/. Because Python searches the script's folder first, it imports your file instead of the SDK.
Fix: rename your file or folder, and delete any __pycache__ folder next to it.
ImportError: cannot import name 'X' from 'anthropic'
Why: usually one of these:
- A typo or wrong capitalization, such as
from anthropic import anthropicorfrom anthropic import AnthropicClient. The correct name isAnthropic. - An old SDK version that does not have the name yet, such as
beta_toolon an old release. - Code written for a different major version.
Fix: check the spelling, run print(anthropic.__version__), and compare with the documentation for your version. Upgrade if needed (Lesson 5).
TypeError: 'module' object is not callable
import anthropic
client = anthropic() # Wrong: anthropic is the module
Fix: call the class, anthropic.Anthropic().
Importing Inside Frequently Called Functions
def ask(prompt):
from anthropic import Anthropic # Imported on every call
client = Anthropic() # And a new client on every call
...
Why it is a problem: the import itself is cached and cheap after the first time, but this pattern usually comes with creating a new client on every call. That discards connection reuse. It also hides the file's dependencies from anyone reading the top of the file.
Fix: import at the top of the module, and create the client once.
Best Practices
- Import at the top of the file, grouped as standard library, third-party, then local modules.
- Prefer
from anthropic import Anthropicfor the client, andanthropic.prefixes for exceptions in mixed-library code. - Never use
from anthropic import *. - Use
anthropic.typesfor type hints, and plain dictionaries for request data. - Centralize SDK setup in one module that creates the client and exposes simple functions to the rest of the application.
- Log
anthropic.__version__at startup or in error reports. - Never name your own files or folders
anthropic.
Exercise
- In a Python shell, import the SDK and print its version.
- List the public names that end with
Errorusingdir(anthropic). - Print
anthropic.AuthenticationError.__mro__and identify its parent classes. - Create the
claude_service.pyandsummarize.pyfiles from the example. Then add aclassify.pythat usesask()to classify the sentence "The app crashes when I upload a PNG" asbug,feature request, orquestion, replying with one word.
Step 2:
import anthropic
errors = [name for name in dir(anthropic) if name.endswith("Error")]
print(errors)
Step 3: the output shows AuthenticationError, APIStatusError, APIError, AnthropicError, and then Python's built-in Exception, BaseException, and object.
Step 4:
"""classify.py"""
from claude_service import ClaudeServiceError, ask
report = "The app crashes when I upload a PNG"
prompt = (
"Classify the following user report as exactly one of: "
"bug, feature request, question. Reply with only the label.\n\n"
f"Report: {report}"
)
try:
print(ask(prompt, max_tokens=1024).strip())
except ClaudeServiceError as error:
print(f"Classification failed: {error}")
Expected output: bug. The generous max_tokens value leaves room for any thinking the model does before answering (Lesson 13).