Decorators in Python

Learn about the decorators in Python and its practical implementation using coding examples.


The Decorator pattern is useful in Python, but there are additional options. For example, we can use monkey-patching— changing the class definition at runtime—to get a similar effect. For example, socket.socket.send = log_send will change the way the built-in socket works. There are sometimes surprising implementation details that can make this unpleasantly complex. Single inheritance, where the optional calculations are done in one large method with a bunch of if statements, could be an option. Multiple inheritance should not be written off just because it’s not suitable for the specific example seen previously.

In Python, it is very common to use this pattern on functions. As we saw in a previous chapter, functions are objects too. In fact, function decoration is so common that Python provides a special syntax to make it easy to apply such decorators to functions.


For example, we can look at the logging example in a more general way. Instead of logging only send calls on sockets, we may find it helpful to log all calls to certain functions or methods. The following example implements a decorator that does just this:

Get hands-on with 1200+ tech skills courses.