Python Function Wrappers and Decorators, Explained with API Examples
A Python function wrapper runs code before and after another function without changing it. This guide builds wrappers and decorators step by step, then uses them for API calls: retries, auth headers, rate limits and caching. Every sample was run on Python 3.14.

TL;DR:
What is a Python function wrapper?
A Python function wrapper takes another function, adds behaviour before or after it, and returns a new function. The@decoratorsyntax applies a wrapper in one line.
Addfunctools.wrapsso the wrapped function keeps its name and docstring.
Your service calls a payments API in twelve places. Each call needs a retry, an auth header and a timeout. Someone copies the same eight lines into every call site. Then the retry logic changes, and you fix it in twelve places, or eleven.
A Python function wrapper fixes this. You write the retry once and apply it with one line. Python is the language most likely to face this problem: 57.9% of respondents to the Stack Overflow 2025 Developer Survey used it.
This guide builds wrappers from scratch, then turns them into four decorators for API calls. Every sample below was run on Python 3.14, and the output shown is real.

What is a Python function wrapper?
A Python function wrapper is a function that wraps another function to add behaviour without editing it. It receives the original function, defines an inner function that calls it, and returns that inner function.
The word "wrapper" means the same thing in plain English: a layer around something that leaves the inside intact. A Python wrapper can log calls, check inputs, time execution, retry failures or cache results. The wrapped function does not know the wrapper exists.
Do not confuse this with an API wrapper. An API wrapper is a client library around an HTTP API. A wrapper function in Python wraps a single function. You often use the second to build the first.
How do you create a wrapper function in Python?
To create a wrapper, define an outer function that takes func. Inside it, define wrapper(*args, **kwargs) that calls func, then return wrapper. The *args, **kwargs signature lets the wrapper accept any arguments and pass them through.
Here is a wrapper applied by hand, without decorator syntax:
Output:
The wrapper works, but look at the last line. The function now reports its name as wrapper and has lost its docstring. Logs, tracebacks and test tools will show the wrong name. The next section fixes that.
What are Python decorators, and why use functools.wraps?
Python decorators are wrappers applied with the @ syntax. functools.wraps copies the original function's name, docstring and metadata onto the wrapper. Writing @log_calls above a function is the same as add = log_calls(add) after it.
The @ syntax arrived with PEP 318 in Python 2.4. It moved the wrapping next to the function definition, where readers can see it.
Output:
The name and docstring are back. functools.wraps also sets __wrapped__, which points to the original function. The last line calls it directly and skips the logging. That attribute matters when you test decorated code.
Rule of thumb: put @functools.wraps(func) on every wrapper you write. It costs one line and prevents confusing logs.
How do you write a decorator with arguments?
A decorator with arguments is a function that returns a decorator. You add one more layer: the outer function takes the settings, the middle one takes func, and the inner one wraps the call.
Output:
@tag("orders-api") first calls tag("orders-api"). That returns decorator, which Python then applies to status. Every API decorator below uses this three-layer shape, so you can set retries, limits or timeouts per function.

How do you write a Python retry decorator with backoff?
A Python retry decorator catches temporary errors, waits, and calls the function again, with the wait growing after each failure. Exponential backoff with jitter stops many clients from retrying at the same moment.
Output:
Three rules keep retries safe:
- Retry only temporary errors. Connection errors, timeouts, 429 and 503 are worth a retry. A 400 or 401 will fail again.
- Retry only idempotent calls. A GET is safe. A POST that creates an order can charge twice unless the API supports idempotency keys.
- Cap the attempts. Unlimited retries turn one outage into a traffic flood.
For production, the tenacity library offers the same pattern with stop, wait and retry conditions. Version 9.2.1 was released on PyPI on 7 Oct 2026. The older backoff library still works, but its last release, 2.2.1, dates from October 2022.
How do you add auth headers with a decorator?
An auth decorator reads a token from the environment and adds it to the request headers. No call site handles secrets. It keeps tokens out of source code and out of every function signature.
Output:
The decorator merges the token into any headers the caller passes. It fails fast with a clear message if the variable is missing. Never paste the token into the code itself. Our guide to hardcoded API keys explains how leaked keys get found and abused.
How do you rate limit API calls on the client side?
A rate limit decorator spaces out calls so your client never sends more than a set number per second. It prevents 429 errors before the server has to send them.
Output:
The first call runs at once, and the next five wait 0.2 seconds each. The lock keeps the limit correct across threads in one process. It does not coordinate across processes or servers; for that, the API side must enforce the limit. Our guide to API rate limiting vs throttling covers how servers do it.
How do you cache API responses with a decorator?
A caching decorator stores each result by its arguments and returns the stored copy until it expires. It cuts repeat calls for data that changes slowly, such as exchange rates or product catalogs.
Output:
Three calls reached the upstream once. The standard library's functools.lru_cache and functools.cache work too, but they never expire entries. Use a time limit for anything an API can change.
In what order should you stack API decorators?
Decorators apply from the bottom up, and the top one runs first on each call. For API calls, put the cache on top, then retry, then rate limit, then auth.
With retry above the rate limiter, retries cannot burst past your limit. With the cache on top, a hit never touches the network.

How do you test a Python function wrapper?
Test the decorator's behaviour through the decorated function, and test the original logic through __wrapped__. Feed the function a scripted sequence of failures so tests run fast with no network.
Output:
The same test_ functions run unchanged under pytest. In real suites, make the sleep injectable or patch time.sleep, so backoff does not slow your tests.
When should you write your own decorator, and when should you not?
Write your own decorator for small, local rules; move shared API policy to a library or to the gateway. A decorator only protects the code that uses it.
Write your own decorator if:
- The rule is specific to one client, such as a tag, a timer or a local cache.
- You want zero dependencies in a small script or library.
- The logic fits in 20 lines and you can test it fully.
Use a library or move the rule to the API layer if:
- You need jitter, stop rules and async support, which tenacity already handles.
- Many teams call the same API. Each client then re-implements auth and limits, and they drift apart.
- The limit must hold across servers. A client-side decorator cannot see other processes.
Server-side rules belong at the gateway. The DigitalAPI API Gateway supports OAuth, OIDC and mTLS, and applies separate rate limits per consumer, including AI agents. Clients keep thin decorators for retries and caching, and the gateway enforces the rest for everyone. If you are choosing a framework for the API itself, see our best Python API frameworks.
See how DigitalAPI enforces auth and rate limits for every API consumer at the gateway → Book a Demo
Key takeaways
- A Python function wrapper adds behaviour around a function without changing it. Decorators apply wrappers with the
@syntax. - Always use
functools.wraps. It keeps the function's name and docstring and exposes__wrapped__for tests. - Decorators with arguments add one layer: settings, then decorator, then wrapper.
- A Python retry decorator needs backoff, jitter and a cap, and should retry only temporary errors on idempotent calls.
- Stack API decorators as cache, retry, rate limit, auth, from top to bottom.
- Client decorators protect one client. Enforce shared auth and limits at the API gateway.
Frequently asked questions
1. What is a wrapper function?
A wrapper function is a function whose main job is to call another function, adding steps before or after the call. In Python, a wrapper takes the original function as an argument, defines an inner function that calls it, and returns that inner function. Wrappers are used for logging, timing, retries, caching and access checks.
2. How do you create a wrapper in Python?
Define an outer function that takes func. Inside it, define wrapper(*args, **kwargs) that runs your extra code and calls func(*args, **kwargs). Return wrapper. Decorate the inner function with functools.wraps(func) to keep the original name and docstring. Apply it with @your_decorator above any function.
3. What does wrapper mean in Python?
In Python, a wrapper is code that surrounds a function, object or library to add behaviour or a simpler interface. A function wrapper wraps one function. An API wrapper is a client library that wraps an HTTP API. A class wrapper wraps an object. In each case, the wrapped code stays unchanged.
4. What is the difference between a wrapper and a decorator in Python?
A wrapper is the inner function that runs around the original call. A decorator is the function that builds and returns that wrapper. The @decorator syntax applies it at definition time. In everyday use, developers often call both "decorators", and the terms overlap.
5. What does functools.wraps do?
functools.wraps copies the original function's metadata onto the wrapper. That includes __name__, __doc__, __module__, __qualname__ and __dict__. It also sets __wrapped__ to the original function. Without it, every decorated function reports its name as wrapper, which confuses logs, tracebacks and tests.
6. How do you write a Python retry decorator?
Write a decorator factory that takes the number of attempts and a base delay. In the wrapper, call the function in a loop. Catch only temporary errors, such as connection errors and timeouts. Sleep with exponential backoff plus random jitter between attempts. Re-raise the error after the last attempt.
7. Should I use tenacity or write my own retry decorator?
Write your own for small scripts and simple rules, since it needs no dependency and fits in about 20 lines. Use tenacity for production services that need async support, stop conditions, custom waits and logging hooks. Tenacity 9.2.1 was the latest version on PyPI on 27 November 2026.
8. Can a Python decorator take arguments?
Yes. Write a function that takes the arguments and returns a decorator. That decorator takes the function and returns the wrapper. Using @retry(times=3) first calls retry(times=3), then applies the returned decorator to the function below it.
Conclusion
A Python function wrapper is a small idea with a large payoff. You write a behaviour once, such as a retry, an auth header, a rate limit or a cache, and apply it with one line.
Start with the four API decorators above and add functools.wraps to each. Test them with scripted failures, not live calls. Stack them in the order shown, so retries respect limits and cache hits skip the network.
Then decide what belongs in the client at all. Rules every consumer must follow, such as authentication and per-consumer limits, are easier to enforce once at the gateway than in every codebase.
Stop hand-rolling auth and rate limits in every client: enforce them at the DigitalAPI gateway. Enforce auth and rate limits at the gateway
Prefer a walkthrough? Book a Demo
One email a fortnight. Worth opening.
A short digest of what we're writing, what we're learning from customers, and the handful of links you'd actually want from us. No tracking pixels.













.avif)
