Decorators For Timing And Retry

Wrap cross-cutting concerns in decorators with functools.wraps so callers keep signatures and docstrings while gaining timing or retry.

PythonResilience

Code

pythonsnippet
51 lines
import functools
import time


def timed(fn):
    @functools.wraps(fn)  # 保留 __name__ / __doc__ / 签名元数据
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            elapsed = (time.perf_counter() - start) * 1000
            print(f'{fn.__name__}: {elapsed:.2f}ms')

    return wrapper


def retry(times: int = 3, delay: float = 0.01):
    def decorate(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            last = None
            for attempt in range(1, times + 1):
                try:
                    return fn(*args, **kwargs)
                except Exception as exc:  # noqa: BLE001 - 演示重试边界
                    last = exc
                    if attempt < times:
                        time.sleep(delay)
            raise last

        return wrapper

    return decorate


attempts = {'count': 0}


@timed
@retry(times=3, delay=0)
def flaky() -> str:
    """Fails twice then succeeds."""
    attempts['count'] += 1
    if attempts['count'] < 3:
        raise RuntimeError('transient failure ' + str(attempts['count']))
    return 'ok after ' + str(attempts['count'])


print(flaky())
print('name/doc preserved:', flaky.__name__, '|', flaky.__doc__)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

flaky: 0.19ms
ok after 3
name/doc preserved: flaky | Fails twice then succeeds.

Inside the snippet

The part worth importing is the functions timed, wrapper, retry and decorate — everything else is wiring.

Iteration happens inside for attempt in range(1, times + 1) — everything outside it runs once. A guard precedes the last and RuntimeError: bad state stops the flow there instead of continuing.

What to watch for

  • The guard attempts['count'] < 3 exits the current step right away with an early raise when its condition holds.

Putting it to use

Signature: def timed(fn)

The demo output is labeled (name/doc preserved:), so every line in the printed output names the step that produced it.

timed is what another module would consume; nothing else here is load-bearing for callers.

Core lines

except Exception as exc:  # noqa: BLE001 - 演示重试边界
    last = exc
    if attempt < times:
        time.sleep(delay)
raise last
return wrapper
return decorate
attempts = {'count': 0}
def wrapper(*args, **kwargs):
    start = time.perf_counter()
    try:
        return fn(*args, **kwargs)
    finally:
        elapsed = (time.perf_counter() - start) * 1000
        print(f'{fn.__name__}: {elapsed:.2f}ms')
def wrapper(*args, **kwargs):
    last = None
    for attempt in range(1, times + 1):
        try:
            return fn(*args, **kwargs)
        except Exception as exc:  # noqa: BLE001 - 演示重试边界
            last = exc
            if attempt < times:
                time.sleep(delay)
    raise last

Interactive Tools for This Topic

FAQ

How does the snippet fail?
The code throws `last` and `RuntimeError` — the guard `attempts['count'] < 3` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `timed`, `wrapper`, `retry` at load time.