Function wrapper

2 snippets across 2 stacks - JavaScript, Python

Also written as wrapper function

JSJavaScript

Higher-Order Functions

JS · Functions
Syntax
function fn(callback) { callback(); }
function fn() { return function() {}; }
Example
function withLogging(fn) {
  return function(...args) {
    console.log(`Calling ${fn.name} with`, args);
    const result = fn(...args);
    console.log(`Result:`, result);
    return result;
  };
}

const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
loggedAdd(3, 4);
Output
"Calling add with [3, 4]"
"Result: 7"

Note Functions that accept or return other functions. The backbone of functional patterns like decorators, middleware, and composition.

PYPython

Decorators

PY · Functions
Syntax
@decorator
def func(): ...
Example
import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__} took {elapsed:.4f}s")
        return result
    return wrapper

@timer
def compute(n):
    return sum(range(n))

compute(1_000_000)
Output
compute took 0.0XXXs

Note Always use @functools.wraps(func) in your wrapper so that the decorated function preserves its name and docstring. Decorators run at import time.

Frequently asked questions

How does JavaScript handle function wrapper?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Higher-Order Functions" snippet in JavaScript uses `function fn(callback) { callback(); }`.
Which code does the JavaScript example use?
The "Higher-Order Functions" snippet uses `function fn(callback) { callback(); }`, from the Functions section of the JavaScript cheat sheet.
Which stacks cover "function wrapper" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Higher-Order Functions": Functions that accept or return other functions. The backbone of functional patterns like decorators, middleware, and composition.