3. Some theory
● Introduced in Python 2.4.
● Decorators can be used to implement the
decorator pattern.
● Decorators are similar to annotations in
Java/C#.
● When compared to C, decorators are comparable
to preprocessor macros.
● Decorators are possible thanks to functions,
like everything else, being objects.
5. Decorators are just syntactic sugar
● A decorator is a function or class that
takes a function as an argument and
returns a replacement callable.
● The ‘@object’ syntax above functions is
not magic;
● It just provides a clean notation.
6. How decorators are being called
Identical behaviour with and without
decorators
Adding ‘logging’ argument:
7. Beginner’s mistake
This function based sleep decorator lacks
nesting.
Calls
broken_sleep_decorator(say_hello)
upon program initialization;
so sleep(1) is always called.
Function is not replaced
8. Working sleep decorator
Defines ‘wrapper’ and returns it as
replacement function
Calls original function
Executes
say_hello = sleep_decorator(say_hello)
Calls wrapper(“Byte”)
Call is equal to:
sleep_decorator(say_hello)(“Byte”)
9. Tunable sleep decorator
Accepts decorator arguments
Accepts function argument
Accepts arguments for function
Calls original function
Calls
tunable_sleep_decorator
(seconds=1)
(say_hello)
Calls wrapper(“Byte”)
Call is equal to:
tunable_sleep_decorator(seconds=1)(say_hello)(“Byte”)
10. Function vs Class decorators
● They can be written to have near
identical behaviour;
● However, classes allow storage of
state.
● It depends on the situation, really.
11. Function vs. class decorators
● Basic function vs. class example
● Note the difference in return values