Decorators
Not met yet
A decorator takes a function and hands back a replacement, usually a wrapper that does something extra and calls the original. @timed above a def is short for weigh = timed(weigh), and it runs once, when the def runs. The wrapper should take *args, **kwargs and pass them through, return the original's result, and use @functools.wraps(func) so the function keeps its name.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks the decorator function itself runs every time the decorated function is called, rather than once when the def runs.
- Thinks the name still refers to the original function after decorating, so the wrapper never runs.
- Thinks a wrapper hands back the original function's result without a return statement.
- Thinks a decorated function keeps its own __name__ without functools.wraps.