runtime

compare approaches one problem · two ways

Compare Approaches

The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.

Wrapper without wraps vs decorator with functools.wrapsbehaves differently

Log every call to a function, then check the function's name and docstring.

what differs

@logged is exactly total = logged(total). Without functools.wraps, the result is named ‘wrapper’ and has no docstring, which confuses debuggers, help() and tools that look functions up by name.

at a glance

approachuse it when
A · plain wrapperNever in shared code: the wrapped function loses its identity.
B · @decorator + wrapsEvery decorator you write.

Watch out: wraps also sets __wrapped__, so inspect.signature and tests can reach the original function.

the outputs

Each approach runs on the same input.

concepts

decoratorsfunctools.wrapshigher-order functions

learn it

Decorators: wrap a function · functools.wraps: keep the function's identity

related comparisons

Memoising: dict vs lru_cache vs cache · Closure vs callable object

A · plain wrapper
B · @decorator + wraps
Compare Python Approaches · Runtime