def debug(func): @functools.wraps(func) def wrapper(*args, **kwargs): args_repr = [repr(a) for a in args] kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] signature = ", ".join(args_repr + kwargs_repr) print(f"Calling {func.__name__}({signature})") result = func(*args, **kwargs) print(f"{func.__name__!r} returned {result!r}") return result return wrapper
Decorators & Metaclasses

Meaning

A decorator that logs function calls and return values for debugging purposes.

Primary Function

Wraps a function to print its call signature and return value each time it is invoked.

Communicative Purpose

Provides transparent debugging information about function inputs and outputs without altering the function's behavior.

Pattern

def debug(func): @functools.wraps(func) def wrapper(*args, **kwargs): ... return wrapper

Core Structure

@functools.wraps(func) def wrapper(*args, **kwargs): ... return wrapper

Função primária

Wraps a function to print its call signature and return value each time it is invoked.

Propósito comunicativo

Provides transparent debugging information about function inputs and outputs without altering the function's behavior.

Situações de gatilho

Used when debugging function behavior, especially during development or testing, to inspect arguments and return values.

Contextos

Applied to functions in development, testing, or debugging sessions within Python codebases.

Padrão

def debug(func): @functools.wraps(func) def wrapper(*args, **kwargs): ... return wrapper

Estrutura central

@functools.wraps(func) def wrapper(*args, **kwargs): ... return wrapper

Slots de substituição

*args, **kwargs, func, args_repr, kwargs_repr, signature, result

Colocados típicos

  • functools.wraps
  • *args
  • **kwargs
  • repr
  • print
  • func.__name__

Substituições comuns

  • replace print with logging.debug
  • use a logger instead of print
  • async variant

Erros comuns

forgetting to return result, omitting functools.wraps, printing instead of returning, causing unintended side effects

Similar / contraste

Similar to a logging decorator; differs from a simple print decorator that does not preserve metadata.

Interferências

Printing may interfere with a function's stdout; avoid in production; may affect performance.

Família do chunk

  • debugging decorator
  • logging decorator
  • function wrapper

Nuance

Preserves the original function's name, docstring, and signature via functools.wraps, making debugging transparent.

Efeito pragmático

Provides clear debugging insight while leaving the function's semantics unchanged.

Dica de memória

Think of a spy that logs every call and return.

Tipo de construção: decorator pattern using functools.wrapsTag de espaçamento: UnknownIdioma?: Sim

Log in to save chunks.