Adapter
An adapter translates one object's interface into another that a caller already expects. It lets you keep a third-party API out of the rest of the program.
Detailed Explanation
Your checkout wants charge(cents: int, currency: str) -> str. Stripe's SDK wants a PaymentIntent with a dict of metadata. An adapter is a small class or function that accepts charge arguments, calls Stripe, and returns the id. The rest of the app never imports Stripe.
That is different from a decorator. A decorator adds behaviour and keeps the same interface. An adapter changes the interface. It may wrap one object (StripeAdapter(client)) or several.
Python makes adapters cheap: you do not need a formal interface. A function is an adapter. A class is an adapter when you need to hold the client and implement several methods (charge, refund, status). A Protocol on the app side documents what adapters must provide.
Adapt at the boundary. Do not let SDK types (stripe.Charge) leak into your domain models. Convert to your own Payment dataclass. Then you can replace Stripe in tests with an in-memory adapter that records calls.
Two-way adapters exist (your object must look like a library's callback). They are still a translation layer. Keep them thin. Business rules do not belong in the adapter; they belong inside the app, tested without the SDK.
struct packing, csv.reader wrapping a file, and pathlib.Path wrapping a string are adapters you already use. The pattern is "make it look like what I wanted".
Code Examples
class Payment:
def __init__(self, cents: int, currency: str):
self.cents = cents
self.currency = currency
class StripeAdapter:
def __init__(self, client):
self.client = client
def charge(self, payment: Payment) -> str:
raw = self.client.create(amount=payment.cents, currency=payment.currency)
return raw["id"]
class FakeClient:
def create(self, amount: int, currency: str) -> dict:
return {"id": f"ch_{amount}_{currency}"}
print(StripeAdapter(FakeClient()).charge(Payment(2500, "usd")))
# ch_2500_usdCommon Gotchas
Returning the SDK object
the adapter did not adapt. Map to your type.
Fat adapters
if the class has business rules, split them out so you can test them without mocks of the SDK.
Catching all exceptions from the vendor
wrap into your `PaymentError` and keep `__cause__` with `from exc`.
A lambda can be an adapter
`charge=lambda p: client.create(...)` until you need a name and tests.