Reuven M. Lerner - Practical decorators - PyCon 2019
Why Stack Overflow recommends it
Stack Overflow users link it when answering or asking about how decorators work, especially for building a mental model of decorators and their closure state.
Recommended by 1 people across 1 different months, 2014 to 2020.
What it is
A PyCon 2019 talk by Reuven M. Lerner on practical uses of Python decorators. It moves beyond the basic mechanics to show real examples, such as rate limiting a function, where decorators make code more readable and maintainable.
What people said
Strong rec srj · 2014-09 · Stack Overflow · on “Decorators with parameters?”
Edit : for an in-depth understanding of the mental model of decorators, take a look at this [this video] awesome Pycon Talk. well worth the 30 minutes. One way of thinking about decorators with arguments is @decorator def foo(*args, **kwargs): pass translates to foo = decorator(foo) So if the decorator had arguments, @decorator_with_args(arg) def foo(*args, **kwargs): pass translates to foo = decorator_with_args(arg)(foo) decorator_with_args is a function which accepts a custom argument and which returns the actual decorator (that will be applied to the decorated function). I use a simple trick with partials to make my decorators easy from functools import partial def _pseudo_decor(fun, argument)
Cites IgnasFunka · 2020-03 · Stack Overflow · on “Persistence of variable value within decorator function scope in python”
Listening to Reuven M. Lerner's PyCon 2019 talk [this video] on decorators, and came across the following example of a decorating function. import time def once_per_minute(func): """A decorator that prevents the decorated func from being invoked more than once per minute""" last_invoked = 0 def wrapper(*args, **kwargs): nonlocal last_invoked elapsed_time = time.time() - last_invoked if elapsed_time < 60: raise Exception(f"Only {elapsed_time} has passed") last_invoked = time.time() return func(*args, **kwargs) return wrapper What caused confusion for me was, why does the last_invoked value persists with every run of the decorated function? I would assume that with every run of the decorated functi
Cites sahinakkaya · 2020-06 · Stack Overflow · on “Understanding how this Python Decorator works”
How can I reference a function inside itself (wrapper.count)? Function bodies are executed only when you call it. By that time, the function is already defined so this is what makes that possible. The following will not give you any error, unless you call it: >>> def foo(): ... non_existing_function() ... And whenever you enter the body of foo , foo is already defined, so you can reference it. This is also what makes recursive calls possible. How wrapper has the method count before wrapper is defined? The question could also be " How could I increment the wrapper.count before it is initialized? " But again, we can answer this in the same way: since function bodies are not executed until we c