Dealing with Side Effects in Decorators

Learn how to deal with side effects in decorators.

In this lesson, we'll learn that it is advisable to avoid side effects in the body of the decorator. There are cases where this might be acceptable, but the bottom line is that if in doubt, decide against it, for the reasons that we're about to get into. Everything that the decorator needs to do, aside from the function that it's decorating, should be placed in the innermost function definition, or there will be problems when it comes to importing. Nonetheless, sometimes these side effects are required (or even desired) to run at import time, and the reverse applies.

We'll see examples of both and where each one applies. If in doubt, err on the side of caution, and delay all side effects until the very last moment, right after the wrapped function is going to be called.

Next, we'll see when it's not a good idea to place extra logic outside the wrapped function.

Incorrect handling of side effects in a decorator

Let's imagine the case of a decorator that was created with the goal of logging when a function started running and then logging its running time:

Get hands-on with 1400+ tech skills courses.