Decorator

2 snippets across 2 stacks — Python, TypeScript

Also written as @decorator · decorators

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.

TSTypeScript

Decorators (TC39 / TS 5.0+)

TS · Classes
syntax
@decorator
class Name { ... }

class Name {
  @decorator accessor prop = value;
}
example
// TS 5.0+ standard decorators (TC39 Stage 3)
function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

function log(
  target: any,
  context: ClassMethodDecoratorContext
) {
  const methodName = String(context.name);
  return function (this: any, ...args: any[]) {
    console.log(`Calling ${methodName} with`, args);
    return target.call(this, ...args);
  };
}

@sealed
class OrderService {
  @log
  processOrder(orderId: string) {
    console.log(`Processing ${orderId}`);
  }
}
output
// Calling processOrder with ["ord_123"]
// Processing ord_123

Note TS 5.0 introduced TC39 standard decorators — these are different from the legacy experimental decorators. Standard decorators receive a context object instead of the old three-parameter signature. Set "experimentalDecorators": false (or omit it) to use the new standard. Legacy decorators are still available with "experimentalDecorators": true.