Import Anthropic

Su Suriya Ravichandran Updated 10 Nov 2026
11 min read ·Lesson 9 of 200

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:

  1. Searches for a module named anthropic in the folders listed in sys.path. These are the script's own folder, the standard library, and the site-packages folder of the active environment.
  2. Runs the package's initialization code the first time it is imported. This defines the client classes, exceptions, and types.
  3. Caches the module in sys.modules. Later imports anywhere in the same program reuse it instead of loading it again.
  4. 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:

TermMeaningExample
PackageA folder of Python modules that can be importedanthropic
ModuleA single importable unit of Python codeanthropic, anthropic.types
SubpackageA package inside a packageanthropic.types
NameAnything defined inside a module: a class, function, or constantAnthropic, 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.RateLimitError cannot 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 RateLimitError or APIError can 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.

StyleExampleBest for
import anthropicanthropic.Anthropic()Files that use many SDK names, or that also use other API libraries
from anthropic import XAnthropic()Small scripts and files that use a few names often
CombinedAnthropic() + anthropic.RateLimitErrorMost 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

NamePurposeLessons
AnthropicSynchronous client for the Claude APIMost lessons
AsyncAnthropicAsynchronous client71–80
AnthropicBedrockMantle, AnthropicBedrockAmazon Bedrock161
AnthropicVertexClaude Models on Google Cloud (Google managed)162
AnthropicGoogleCloudClaude Models on Google Cloud (Anthropic managed)162
AnthropicAWSClaude Platform on AWS161
AnthropicFoundryMicrosoft Foundry163

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

NamePurpose
DefaultHttpxClientCustomize the sync client's HTTP layer, for example with a proxy, while keeping SDK defaults
DefaultAsyncHttpxClientThe same for the async client
DefaultAioHttpClientThe aiohttp backend for the async client (needs the aiohttp extra)
beta_toolDecorator 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
TypeWhat it describes
MessageA complete response from client.messages.create()
TextBlockA text content block inside message.content
MessageParamOne 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"}) and MessageParam only as an annotation. Calling MessageParam(...) like a constructor raises TypeError (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.py imports anthropic. Other modules import ask and ClaudeServiceError. If the SDK changes in a future major version, there is one file to update.
  • The client is created once, when claude_service is first imported. Thanks to Python's module cache (sys.modules), every other module that imports claude_service shares the same client object.
  • extract_text() joins the text blocks instead of reading message.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.APIError catches every API-related failure: connection problems, timeouts, and error status codes. It re-raises it as the application's own ClaudeServiceError, so callers do not need to know about SDK exceptions. from error keeps 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 anthropic or from anthropic import AnthropicClient. The correct name is Anthropic.
  • An old SDK version that does not have the name yet, such as beta_tool on 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 Anthropic for the client, and anthropic. prefixes for exceptions in mixed-library code.
  • Never use from anthropic import *.
  • Use anthropic.types for 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

  1. In a Python shell, import the SDK and print its version.
  2. List the public names that end with Error using dir(anthropic).
  3. Print anthropic.AuthenticationError.__mro__ and identify its parent classes.
  4. Create the claude_service.py and summarize.py files from the example. Then add a classify.py that uses ask() to classify the sentence "The app crashes when I upload a PNG" as bug, feature request, or question, replying with one word.
Show answers

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).

0 Comments

Reviewed before they appear

No comments yet.

Anthropic SDK Using Python
Anthropic SDK Intro Claude API Intro SDK Requirements Install Anthropic SDK Upgrade the SDK Create an API Key Set API Keys Use Environment Variables Import Anthropic Create a Client Send Your First Message Choose a Claude Model Set Max Tokens Read a Response Print Response Text Understand Message Blocks Use System Prompts Send User Messages Set Temperature Handle Stop Reasons Messages API Intro Create Messages Use Message Roles Send Conversation History Continue a Conversation Build a Chat Loop Reset Chat History Use Multiple Turns Inspect Message IDs Read Usage Data Write Clear Prompts Set a System Prompt Add Context to Prompts Use Prompt Templates Add Examples to Prompts Request JSON Output Use XML Tags Control Response Length Improve Prompt Quality Avoid Prompt Injection Read Text Blocks Read Content Blocks Check Stop Reasons Count Input Tokens Count Output Tokens Count Tokens Before Sending Limit Output Tokens Use Stop Sequences Read Request IDs Parse API Responses Streaming Intro Stream Text Output Use Stream Events Use Stream Helpers Get Final Messages Stream Async Responses Handle Stream Errors Build a Live Chat Stream Long Responses Close Streams Safely Build a Chatbot Keep Chat History Manage Chat Sessions Add Chat Memory Build a CLI Chatbot Build a Web Chatbot Use Flask with Claude Use FastAPI with Claude Return JSON from an API Add Chat Error Messages Async SDK Intro Create an Async Client Send Async Messages Use asyncio Run Parallel Requests Stream Async Text Handle Async Errors Set Async Timeouts Close Async Clients Choose Sync or Async Tool Use Intro Define a Tool Create Tool Schemas Send Tools to Claude Read Tool Calls Run Python Tools Return Tool Results Continue After Tool Use Control Tool Choice Handle Tool Errors Use the beta_tool Decorator Create a Tool Runner Add Tool Docstrings Validate Tool Inputs Use Multiple Tools Limit Tool Calls Log Tool Activity Build a Weather Tool Build a Search Tool Build a Calculator Tool Structured Output Intro Request JSON Data Validate JSON Output Use Pydantic Models Handle Invalid JSON Extract Fields from Text Generate Typed Data Use Image URLs Send Base64 Images Read PDFs with Claude Use Output Schemas Build Data Extraction Test Structured Responses Send Image Inputs Upload Files Use File IDs Process Text Files Summarize Documents Extract Table Data Handle File Errors Read Cache Usage Reduce Repeated Input Costs Debug Cache Misses Prompt Caching Intro Enable Prompt Caching Cache System Prompts Cache Long Context Test Cache Performance Use Cache Breakpoints Cache Best Practices Message Batches Intro Create a Message Batch Set Batch IDs Check Batch Status List Message Batches Get Batch Results Process Batch Outputs Handle Failed Batch Items Use Batches for Bulk Tasks Compare Batches and Requests Handle API Errors Handle Rate Limits Retry Failed Requests Set Request Timeouts Handle Network Errors Use Exponential Backoff Build Reliable API Calls Use Extended Thinking Log API Errors Track Request IDs Paginate API Results Set Thinking Budgets Read Thinking Blocks Use Tool Search Use Web Search Tools Use Computer Tools Use Citations Use Token Counting Read Raw Responses Set Custom Headers Use Claude on AWS Bedrock Use Claude on Vertex AI Use Claude on Microsoft Foundry Configure Cloud Credentials Choose a Cloud Provider Compare API Integrations Configure Provider Clients Handle Cloud Errors Use Cloud SDK Extras Deploy Cloud Apps Protect API Keys Use a .env File Ignore Secrets in Git Validate User Input Reduce Prompt Injection Limit Tool Permissions Avoid Unsafe Tool Calls Sanitize Tool Results Set Usage Limits Review Security Logs Test SDK Functions Mock API Responses Test Error Handling Test Streaming Code Measure Token Usage Track API Costs Configure Logging Deploy with Docker Deploy a FastAPI App Monitor Production Apps Build a Claude Chatbot Build a Text Summarizer Build a Code Explainer Build a JSON Extractor Build a PDF Assistant Build a Streaming Chat App Build a Tool-Calling Agent Build a Batch Processor Build a Research Assistant Build a Claude API Dashboard
Ask about this post
AI Ask about this post

Ask questions about Import Anthropic and get answers drawn from it.

Signed-in readers only.