Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Decorators 101
+
+
In this tutorial on decorators, we’ll look at what they are and how to create and use them. Decorators provide a simple syntax for calling higher-order functions.
+
By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
+
This sounds confusing, but it’s really not, especially after you’ve seen a few examples of how decorators work. You can find all the examples from this article here.
Before you can understand decorators, you must first understand how functions work. For our purposes, a function returns a value based on the given arguments. Here is a very simple example:
In general, functions in Python may also have side effects rather than just turning an input into an output. The print() function is a basic example of this: it returnsNone while having the side effect of outputting something to the console. However, to understand decorators, it is enough to think about functions as something that turns given arguments into a value.
+
+
Note: In functional programming, you work (almost) only with pure functions without side effects. While not a purely functional language, Python supports many of the functional programming concepts, including functions as first-class objects.
defsay_hello(name):
+ returnf"Hello {name}"
+
+defbe_awesome(name):
+ returnf"Yo {name}, together we are the awesomest!"
+
+defgreet_bob(greeter_func):
+ returngreeter_func("Bob")
+
+
Here, say_hello() and be_awesome() are regular functions that expect a name given as a string. The greet_bob() function however, expects a function as its argument. We can, for instance, pass it the say_hello() or the be_awesome() function:
+
>>>
>>> greet_bob(say_hello)
+'Hello Bob'
+
+>>> greet_bob(be_awesome)
+'Yo Bob, together we are the awesomest!'
+
+
Note that greet_bob(say_hello) refers to two functions, but in different ways: greet_bob() and say_hello. The say_hello function is named without parentheses. This means that only a reference to the function is passed. The function is not executed. The greet_bob() function, on the other hand, is written with parentheses, so it will be called as usual.
+
Inner Functions
+
It’s possible to define functionsinside other functions. Such functions are called inner functions. Here’s an example of a function with two inner functions:
+
defparent():
+ print("Printing from the parent() function")
+
+ deffirst_child():
+ print("Printing from the first_child() function")
+
+ defsecond_child():
+ print("Printing from the second_child() function")
+
+ second_child()
+ first_child()
+
+
What happens when you call the parent() function? Think about this for a minute. The output will be as follows:
+
>>>
>>> parent()
+Printing from the parent() function
+Printing from the second_child() function
+Printing from the first_child() function
+
+
Note that the order in which the inner functions are defined does not matter. Like with any other functions, the printing only happens when the inner functions are executed.
+
Furthermore, the inner functions are not defined until the parent function is called. They are locally scoped to parent(): they only exist inside the parent() function as local variables. Try calling first_child(). You should get an error:
+
Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+NameError: name 'first_child' is not defined
+
+
Whenever you call parent(), the inner functions first_child() and second_child() are also called. But because of their local scope, they aren’t available outside of the parent() function.
Python also allows you to use functions as return values. The following example returns one of the inner functions from the outer parent() function:
+
defparent(num):
+ deffirst_child():
+ return"Hi, I am Emma"
+
+ defsecond_child():
+ return"Call me Liam"
+
+ ifnum==1:
+ returnfirst_child
+ else:
+ returnsecond_child
+
+
Note that you are returning first_child without the parentheses. Recall that this means that you are returning a reference to the function first_child. In contrast first_child() with parentheses refers to the result of evaluating the function. This can be seen in the following example:
+
>>>
>>> first=parent(1)
+>>> second=parent(2)
+
+>>> first
+<function parent.<locals>.first_child at 0x7f599f1e2e18>
+
+>>> second
+<function parent.<locals>.second_child at 0x7f599dad5268>
+
+
The somewhat cryptic output simply means that the first variable refers to the local first_child() function inside of parent(), while second points to second_child().
+
You can now use first and second as if they are regular functions, even though the functions they point to can’t be accessed directly:
+
>>>
>>> first()
+'Hi, I am Emma'
+
+>>> second()
+'Call me Liam'
+
+
Finally, note that in the earlier example you executed the inner functions within the parent function, for instance first_child(). However, in this last example, you did not add parentheses to the inner functions—first_child—upon returning. That way, you got a reference to each function that you could call in the future. Make sense?
+
Simple Decorators
+
Now that you’ve seen that functions are just like any other object in Python, you’re ready to move on and see the magical beast that is the Python decorator. Let’s start with an example:
+
defmy_decorator(func):
+ defwrapper():
+ print("Something is happening before the function is called.")
+ func()
+ print("Something is happening after the function is called.")
+ returnwrapper
+
+defsay_whee():
+ print("Whee!")
+
+say_whee=my_decorator(say_whee)
+
+
Can you guess what happens when you call say_whee()? Try it:
+
>>>
>>> say_whee()
+Something is happening before the function is called.
+Whee!
+Something is happening after the function is called.
+
+
To understand what’s going on here, look back at the previous examples. We are literally just applying everything you have learned so far.
+
The so-called decoration happens at the following line:
+
say_whee=my_decorator(say_whee)
+
+
In effect, the name say_whee now points to the wrapper() inner function. Remember that you return wrapper as a function when you call my_decorator(say_whee):
+
>>>
>>> say_whee
+<function my_decorator.<locals>.wrapper at 0x7f3c5dfd42f0>
+
+
However, wrapper() has a reference to the original say_whee() as func, and calls that function between the two calls to print().
+
Put simply: decorators wrap a function, modifying its behavior.
+
Before moving on, let’s have a look at a second example. Because wrapper() is a regular Python function, the way a decorator modifies a function can change dynamically. So as not to disturb your neighbors, the following example will only run the decorated code during the day:
The way you decorated say_whee() above is a little clunky. First of all, you end up typing the name say_whee three times. In addition, the decoration gets a bit hidden away below the definition of the function.
+
Instead, Python allows you to use decorators in a simpler way with the @ symbol, sometimes called the “pie” syntax. The following example does the exact same thing as the first decorator example:
+
defmy_decorator(func):
+ defwrapper():
+ print("Something is happening before the function is called.")
+ func()
+ print("Something is happening after the function is called.")
+ returnwrapper
+
+@my_decorator
+defsay_whee():
+ print("Whee!")
+
+
So, @my_decorator is just an easier way of saying say_whee = my_decorator(say_whee). It’s how you apply a decorator to a function.
+
Reusing Decorators
+
Recall that a decorator is just a regular Python function. All the usual tools for easy reusability are available. Let’s move the decorator to its own module that can be used in many other functions.
+
Create a file called decorators.py with the following content:
Note: You can name your inner function whatever you want, and a generic name like wrapper() is usually okay. You’ll see a lot of decorators in this article. To keep them apart, we’ll name the inner function with the same name as the decorator but with a wrapper_ prefix.
+
+
You can now use this new decorator in other files by doing a regular import:
>>> greet("World")
+Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+TypeError: wrapper_do_twice() takes 0 positional arguments but 1 was given
+
+
The problem is that the inner function wrapper_do_twice() does not take any arguments, but name="World" was passed to it. You could fix this by letting wrapper_do_twice() accept one argument, but then it would not work for the say_whee() function you created earlier.
+
The solution is to use *args and **kwargs in the inner wrapper function. Then it will accept an arbitrary number of positional and keyword arguments. Rewrite decorators.py as follows:
The wrapper_do_twice() inner function now accepts any number of arguments and passes them on to the function it decorates. Now both your say_whee() and greet() examples works:
+
>>>
>>> say_whee()
+Whee!
+Whee!
+
+>>> greet("World")
+Hello World
+Hello World
+
What happens to the return value of decorated functions? Well, that’s up to the decorator to decide. Let’s say you decorate a simple function as follows:
A great convenience when working with Python, especially in the interactive shell, is its powerful introspection ability. Introspection is the ability of an object to know about its own attributes at runtime. For instance, a function knows its own name and documentation:
+
>>>
>>> print
+<built-in function print>
+
+>>> print.__name__
+'print'
+
+>>> help(print)
+Help on built-in function print in module builtins:
+
+print(...)
+ <full help message>
+
+
The introspection works for functions you define yourself as well:
+
>>>
>>> say_whee
+<function do_twice.<locals>.wrapper_do_twice at 0x7f43700e52f0>
+
+>>> say_whee.__name__
+'wrapper_do_twice'
+
+>>> help(say_whee)
+Help on function wrapper_do_twice in module decorators:
+
+wrapper_do_twice()
+
+
However, after being decorated, say_whee() has gotten very confused about its identity. It now reports being the wrapper_do_twice() inner function inside the do_twice() decorator. Although technically true, this is not very useful information.
+
To fix this, decorators should use the @functools.wraps decorator, which will preserve information about the original function. Update decorators.py again:
You do not need to change anything about the decorated say_whee() function:
+
>>>
>>> say_whee
+<function say_whee at 0x7ff79a60f2f0>
+
+>>> say_whee.__name__
+'say_whee'
+
+>>> help(say_whee)
+Help on function say_whee in module whee:
+
+say_whee()
+
+
Much better! Now say_whee() is still itself after decoration.
+
+
Technical Detail: The @functools.wraps decorator uses the function functools.update_wrapper() to update special attributes like __name__ and __doc__ that are used in the introspection.
Let’s look at a few more useful examples of decorators. You’ll notice that they’ll mainly follow the same pattern that you’ve learned so far:
+
importfunctools
+
+defdecorator(func):
+ @functools.wraps(func)
+ defwrapper_decorator(*args,**kwargs):
+ # Do something before
+ value=func(*args,**kwargs)
+ # Do something after
+ returnvalue
+ returnwrapper_decorator
+
+
This formula is a good boilerplate template for building more complex decorators.
+
+
Note: In later examples, we will assume that these decorators are saved in your decorators.py file as well. Recall that you can download all the examples in this tutorial.
This decorator works by storing the time just before the function starts running (at the line marked # 1) and just after the function finishes (at # 2). The time the function takes is then the difference between the two (at # 3). We use the time.perf_counter() function, which does a good job of measuring time intervals. Here are some examples of timings:
+
>>>
>>> waste_some_time(1)
+Finished 'waste_some_time' in 0.0010 secs
+
+>>> waste_some_time(999)
+Finished 'waste_some_time' in 0.3260 secs
+
+
Run it yourself. Work through the code line by line. Make sure you understand how it works. Don’t worry if you don’t get it, though. Decorators are advanced beings. Try to sleep on it or make a drawing of the program flow.
+
+
Note: The @timer decorator is great if you just want to get an idea about the runtime of your functions. If you want to do more precise measurements of code, you should instead consider the timeit module in the standard library. It temporarily disables garbage collection and runs multiple trials to strip out noise from quick function calls.
+
+
Debugging Code
+
The following @debug decorator will print the arguments a function is called with as well as its return value every time the function is called:
+
importfunctools
+
+defdebug(func):
+ """Print the function signature and return value"""
+ @functools.wraps(func)
+ defwrapper_debug(*args,**kwargs):
+ args_repr=[repr(a)forainargs]# 1
+ kwargs_repr=[f"{k}={v!r}"fork,vinkwargs.items()]# 2
+ signature=", ".join(args_repr+kwargs_repr)# 3
+ print(f"Calling {func.__name__}({signature})")
+ value=func(*args,**kwargs)
+ print(f"{func.__name__!r} returned {value!r}")# 4
+ returnvalue
+ returnwrapper_debug
+
+
The signature is created by joining the string representations of all the arguments. The numbers in the following list correspond to the numbered comments in the code:
+
+
Create a list of the positional arguments. Use repr() to get a nice string representing each argument.
+
Create a list of the keyword arguments. The f-string formats each argument as key=value where the !r specifier means that repr() is used to represent the value.
+
The lists of positional and keyword arguments is joined together to one signature string with each argument separated by a comma.
+
The return value is printed after the function is executed.
+
+
Let’s see how the decorator works in practice by applying it to a simple function with one position and one keyword argument:
+
@debug
+defmake_greeting(name,age=None):
+ ifageisNone:
+ returnf"Howdy {name}!"
+ else:
+ returnf"Whoa {name}! {age} already, you are growing up!"
+
+
Note how the @debug decorator prints the signature and return value of the make_greeting() function:
+
>>>
>>> make_greeting("Benjamin")
+Calling make_greeting('Benjamin')
+'make_greeting' returned 'Howdy Benjamin!'
+'Howdy Benjamin!'
+
+>>> make_greeting("Richard",age=112)
+Calling make_greeting('Richard', age=112)
+'make_greeting' returned 'Whoa Richard! 112 already, you are growing up!'
+'Whoa Richard! 112 already, you are growing up!'
+
+>>> make_greeting(name="Dorrisile",age=116)
+Calling make_greeting(name='Dorrisile', age=116)
+'make_greeting' returned 'Whoa Dorrisile! 116 already, you are growing up!'
+'Whoa Dorrisile! 116 already, you are growing up!'
+
+
This example might not seem immediately useful since the @debug decorator just repeats what you just wrote. It’s more powerful when applied to small convenience functions that you don’t call directly yourself.
importmath
+fromdecoratorsimportdebug
+
+# Apply a decorator to a standard library function
+math.factorial=debug(math.factorial)
+
+defapproximate_e(terms=18):
+ returnsum(1/math.factorial(n)forninrange(terms))
+
+
This example also shows how you can apply a decorator to a function that has already been defined. The approximation of e is based on the following series expansion:
+
+
When calling the approximate_e() function, you can see the @debug decorator at work:
+
>>>
>>> approximate_e(5)
+Calling factorial(0)
+'factorial' returned 1
+Calling factorial(1)
+'factorial' returned 1
+Calling factorial(2)
+'factorial' returned 2
+Calling factorial(3)
+'factorial' returned 6
+Calling factorial(4)
+'factorial' returned 24
+2.708333333333333
+
+
In this example, you get a decent approximation to the true value e = 2.718281828, adding only 5 terms.
This next example might not seem very useful. Why would you want to slow down your Python code? Probably the most common use case is that you want to rate-limit a function that continuously checks whether a resource—like a web page—has changed. The @slow_down decorator will sleep one second before it calls the decorated function:
To see the effect of the @slow_down decorator, you really need to run the example yourself:
+
>>>
>>> countdown(3)
+3
+2
+1
+Liftoff!
+
+
+
Note: The countdown() function is a recursive function. In other words, it’s a function calling itself. To learn more about recursive functions in Python, see our guide on Thinking Recursively in Python.
+
+
The @slow_down decorator always sleeps for one second. Later, you’ll see how to control the rate by passing an argument to the decorator.
+
Registering Plugins
+
Decorators don’t have to wrap the function they’re decorating. They can also simply register that a function exists and return it unwrapped. This can be used, for instance, to create a light-weight plug-in architecture:
+
importrandom
+PLUGINS=dict()
+
+defregister(func):
+ """Register a function as a plug-in"""
+ PLUGINS[func.__name__]=func
+ returnfunc
+
+@register
+defsay_hello(name):
+ returnf"Hello {name}"
+
+@register
+defbe_awesome(name):
+ returnf"Yo {name}, together we are the awesomest!"
+
+defrandomly_greet(name):
+ greeter,greeter_func=random.choice(list(PLUGINS.items()))
+ print(f"Using {greeter!r}")
+ returngreeter_func(name)
+
+
The @register decorator simply stores a reference to the decorated function in the global PLUGINS dict. Note that you do not have to write an inner function or use @functools.wraps in this example because you are returning the original function unmodified.
+
The randomly_greet() function randomly chooses one of the registered functions to use. Note that the PLUGINS dictionary already contains references to each function object that is registered as a plugin:
The main benefit of this simple plugin architecture is that you do not need to maintain a list of which plugins exist. That list is created when the plugins register themselves. This makes it trivial to add a new plugin: just define the function and decorate it with @register.
+
If you are familiar with globals() in Python, you might see some similarities to how the plugin architecture works. globals() gives access to all global variables in the current scope, including your plugins:
+
>>>
>>> globals()
+{..., # Lots of variables not shown here.
+ 'say_hello': <function say_hello at 0x7f768eae6730>,
+ 'be_awesome': <function be_awesome at 0x7f768eae67b8>,
+ 'randomly_greet': <function randomly_greet at 0x7f768eae6840>}
+
+
Using the @register decorator, you can create your own curated list of interesting variables, effectively hand-picking some functions from globals().
+
Is the User Logged In?
+
The final example before moving on to some fancier decorators is commonly used when working with a web framework. In this example, we are using Flask to set up a /secret web page that should only be visible to users that are logged in or otherwise authenticated:
+
fromflaskimportFlask,g,request,redirect,url_for
+importfunctools
+app=Flask(__name__)
+
+deflogin_required(func):
+ """Make sure user is logged in before proceeding"""
+ @functools.wraps(func)
+ defwrapper_login_required(*args,**kwargs):
+ ifg.userisNone:
+ returnredirect(url_for("login",next=request.url))
+ returnfunc(*args,**kwargs)
+ returnwrapper_login_required
+
+@app.route("/secret")
+@login_required
+defsecret():
+ ...
+
+
While this gives an idea about how to add authentication to your web framework, you should usually not write these types of decorators yourself. For Flask, you can use the Flask-Login extension instead, which adds more security and functionality.
So far, you’ve seen how to create simple decorators. You already have a pretty good understanding of what decorators are and how they work. Feel free to take a break from this article to practice everything you’ve learned.
+
In the second part of this tutorial, we’ll explore more advanced features, including how to use the following:
There are two different ways you can use decorators on classes. The first one is very close to what you have already done with functions: you can decorate the methods of a class. This was one of the motivations for introducing decorators back in the day.
+
Some commonly used decorators that are even built-ins in Python are @classmethod, @staticmethod, and @property. The @classmethod and @staticmethod decorators are used to define methods inside a class namespace that are not connected to a particular instance of that class. The @property decorator is used to customize getters and setters for class attributes. Expand the box below for an example using these decorators.
+
+
+
+
+
+
+
The following definition of a Circle class uses the @classmethod, @staticmethod, and @property decorators:
+
classCircle:
+ def__init__(self,radius):
+ self._radius=radius
+
+ @property
+ defradius(self):
+ """Get value of radius"""
+ returnself._radius
+
+ @radius.setter
+ defradius(self,value):
+ """Set radius, raise error if negative"""
+ ifvalue>=0:
+ self._radius=value
+ else:
+ raiseValueError("Radius must be positive")
+
+ @property
+ defarea(self):
+ """Calculate area inside circle"""
+ returnself.pi()*self.radius**2
+
+ defcylinder_volume(self,height):
+ """Calculate volume of cylinder with circle as base"""
+ returnself.area*height
+
+ @classmethod
+ defunit_circle(cls):
+ """Factory method creating a circle with radius 1"""
+ returncls(1)
+
+ @staticmethod
+ defpi():
+ """Value of π, could use math.pi instead though"""
+ return3.1415926535
+
+
In this class:
+
+
.cylinder_volume() is a regular method.
+
.radius is a mutable property: it can be set to a different value. However, by defining a setter method, we can do some error testing to make sure it’s not set to a nonsensical negative number. Properties are accessed as attributes without parentheses.
+
.area is an immutable property: properties without .setter() methods can’t be changed. Even though it is defined as a method, it can be retrieved as an attribute without parentheses.
+
.unit_circle() is a class method. It’s not bound to one particular instance of Circle. Class methods are often used as factory methods that can create specific instances of the class.
+
.pi() is a static method. It’s not really dependent on the Circle class, except that it is part of its namespace. Static methods can be called on either an instance or the class.
+
+
The Circle class can for example be used as follows:
The meaning of the syntax is similar to the function decorators. In the example above, you could have done the decoration by writing PlayingCard = dataclass(PlayingCard).
+
A common use of class decorators is to be a simpler alternative to some use-cases of metaclasses. In both cases, you are changing the definition of a class dynamically.
+
Writing a class decorator is very similar to writing a function decorator. The only difference is that the decorator will receive a class and not a function as an argument. In fact, all the decorators you saw above will work as class decorators. When you are using them on a class instead of a function, their effect might not be what you want. In the following example, the @timer decorator is applied to a class:
Think about this as the decorators being executed in the order they are listed. In other words, @debug calls @do_twice, which calls greet(), or debug(do_twice(greet())):
+
>>>
>>> greet("Eva")
+Calling greet('Eva')
+Hello Eva
+Hello Eva
+'greet' returned None
+
+
Observe the difference if we change the order of @debug and @do_twice:
In this case, @do_twice will be applied to @debug as well:
+
>>>
>>> greet("Eva")
+Calling greet('Eva')
+Hello Eva
+'greet' returned None
+Calling greet('Eva')
+Hello Eva
+'greet' returned None
+
+
Decorators With Arguments
+
Sometimes, it’s useful to pass arguments to your decorators. For instance, @do_twice could be extended to a @repeat(num_times) decorator. The number of times to execute the decorated function could then be given as an argument.
>>> greet("World")
+Hello World
+Hello World
+Hello World
+Hello World
+
+
Think about how you could achieve this.
+
So far, the name written after the @ has referred to a function object that can be called with another function. To be consistent, you then need repeat(num_times=4) to return a function object that can act as a decorator. Luckily, you already know how to return functions! In general, you want something like the following:
+
defrepeat(num_times):
+ defdecorator_repeat(func):
+ ...# Create and return a wrapper function
+ returndecorator_repeat
+
+
Typically, the decorator creates and returns an inner wrapper function, so writing the example out in full will give you an inner function within an inner function. While this might sound like the programming equivalent of the Inception movie, we’ll untangle it all in a moment:
It looks a little messy, but we have only put the same decorator pattern you have seen many times by now inside one additional def that handles the arguments to the decorator. Let’s start with the innermost function:
This wrapper_repeat() function takes arbitrary arguments and returns the value of the decorated function, func(). This wrapper function also contains the loop that calls the decorated function num_times times. This is no different from the earlier wrapper functions you have seen, except that it is using the num_times parameter that must be supplied from the outside.
Again, decorator_repeat() looks exactly like the decorator functions you have written earlier, except that it’s named differently. That’s because we reserve the base name—repeat()—for the outermost function, which is the one the user will call.
+
As you have already seen, the outermost function returns a reference to the decorator function:
There are a few subtle things happening in the repeat() function:
+
+
Defining decorator_repeat() as an inner function means that repeat() will refer to a function object—decorator_repeat. Earlier, we used repeat without parentheses to refer to the function object. The added parentheses are necessary when defining decorators that take arguments.
+
The num_times argument is seemingly not used in repeat() itself. But by passing num_times a closure is created where the value of num_times is stored until it will be used later by wrapper_repeat().
+
+
With everything set up, let’s see if the results are as expected:
With a little bit of care, you can also define decorators that can be used both with and without arguments. Most likely, you don’t need this, but it is nice to have the flexibility.
+
As you saw in the previous section, when a decorator uses arguments, you need to add an extra outer function. The challenge is for your code to figure out if the decorator has been called with or without arguments.
+
Since the function to decorate is only passed in directly if the decorator is called without arguments, the function must be an optional argument. This means that the decorator arguments must all be specified by keyword. You can enforce this with the special * syntax, which means that all following parameters are keyword-only:
Here, the _func argument acts as a marker, noting whether the decorator has been called with arguments or not:
+
+
If name has been called without arguments, the decorated function will be passed in as _func. If it has been called with arguments, then _func will be None, and some of the keyword arguments may have been changed from their default values. The * in the argument list means that the remaining arguments can’t be called as positional arguments.
+
In this case, the decorator was called with arguments. Return a decorator function that can read and return a function.
+
In this case, the decorator was called without arguments. Apply the decorator to the function immediately.
+
+
Using this boilerplate on the @repeat decorator in the previous section, you can write the following:
Sometimes, it’s useful to have a decorator that can keep track of state. As a simple example, we will create a decorator that counts the number of times a function is called.
+
+
Note: In the beginning of this guide, we talked about pure functions returning a value based on given arguments. Stateful decorators are quite the opposite, where the return value will depend on the current state, as well as the given arguments.
+
+
In the next section, you will see how to use classes to keep state. But in simple cases, you can also get away with using function attributes:
The typical way to maintain state is by using classes. In this section, you’ll see how to rewrite the @count_calls example from the previous section using a class as a decorator.
+
Recall that the decorator syntax @my_decorator is just an easier way of saying func = my_decorator(func). Therefore, if my_decorator is a class, it needs to take func as an argument in its .__init__() method. Furthermore, the class instance needs to be callable so that it can stand in for the decorated function.
+
For a class instance to be callable, you implement the special .__call__() method:
The .__init__() method must store a reference to the function and can do any other necessary initialization. The .__call__() method will be called instead of the decorated function. It does essentially the same thing as the wrapper() function in our earlier examples. Note that you need to use the functools.update_wrapper() function instead of @functools.wraps.
+
This @CountCalls decorator works the same as the one in the previous section:
+
>>>
>>> say_whee()
+Call 1 of 'say_whee'
+Whee!
+
+>>> say_whee()
+Call 2 of 'say_whee'
+Whee!
+
+>>> say_whee.num_calls
+2
+
+
More Real World Examples
+
We’ve come a far way now, having figured out how to create all kinds of decorators. Let’s wrap it up, putting our newfound knowledge into creating a few more examples that might actually be useful in the real world.
+
Slowing Down Code, Revisited
+
As noted earlier, our previous implementation of @slow_down always sleeps for one second. Now you know how to add parameters to decorators, so let’s rewrite @slow_down using an optional rate argument that controls how long it sleeps:
+
importfunctools
+importtime
+
+defslow_down(_func=None,*,rate=1):
+ """Sleep given amount of seconds before calling the function"""
+ defdecorator_slow_down(func):
+ @functools.wraps(func)
+ defwrapper_slow_down(*args,**kwargs):
+ time.sleep(rate)
+ returnfunc(*args,**kwargs)
+ returnwrapper_slow_down
+
+ if_funcisNone:
+ returndecorator_slow_down
+ else:
+ returndecorator_slow_down(_func)
+
+
We’re using the boilerplate introduced in the Both Please, But Never Mind the Bread section to make @slow_down callable both with and without arguments. The same recursive countdown() function as earlier now sleeps two seconds between each count:
As before, you must run the example yourself to see the effect of the decorator:
+
>>>
>>> countdown(3)
+3
+2
+1
+Liftoff!
+
+
Creating Singletons
+
A singleton is a class with only one instance. There are several singletons in Python that you use frequently, including None, True, and False. It is the fact that None is a singleton that allows you to compare for None using the is keyword, like you saw in the Both Please section:
Using is returns True only for objects that are the exact same instance. The following @singleton decorator turns a class into a singleton by storing the first instance of the class as an attribute. Later attempts at creating an instance simply return the stored instance:
+
importfunctools
+
+defsingleton(cls):
+ """Make a class a Singleton class (only one instance)"""
+ @functools.wraps(cls)
+ defwrapper_singleton(*args,**kwargs):
+ ifnotwrapper_singleton.instance:
+ wrapper_singleton.instance=cls(*args,**kwargs)
+ returnwrapper_singleton.instance
+ wrapper_singleton.instance=None
+ returnwrapper_singleton
+
+@singleton
+classTheOne:
+ pass
+
+
As you see, this class decorator follows the same template as our function decorators. The only difference is that we are using cls instead of func as the parameter name to indicate that it is meant to be a class decorator.
It seems clear that first_one is indeed the exact same instance as another_one.
+
+
Note: Singleton classes are not really used as often in Python as in other languages. The effect of a singleton is usually better implemented as a global variable in a module.
While the implementation is simple, its runtime performance is terrible:
+
>>>
>>> fibonacci(10)
+<Lots of output from count_calls>
+55
+
+>>> fibonacci.num_calls
+177
+
+
To calculate the tenth Fibonacci number, you should really only need to calculate the preceding Fibonacci numbers, but this implementation somehow needs a whopping 177 calculations. It gets worse quickly: 21891 calculations are needed for fibonacci(20) and almost 2.7 million calculations for the 30th number. This is because the code keeps recalculating Fibonacci numbers that are already known.
+
The usual solution is to implement Fibonacci numbers using a for loop and a lookup table. However, simple caching of the calculations will also do the trick:
The cache works as a lookup table, so now fibonacci() only does the necessary calculations once:
+
>>>
>>> fibonacci(10)
+Call 1 of 'fibonacci'
+...
+Call 11 of 'fibonacci'
+55
+
+>>> fibonacci(8)
+21
+
+
Note that in the final call to fibonacci(8), no new calculations were needed, since the eighth Fibonacci number had already been calculated for fibonacci(10).
The maxsize parameter specifies how many recent calls are cached. The default value is 128, but you can specify maxsize=None to cache all function calls. However, be aware that this can cause memory problems if you are caching many large objects.
+
You can use the .cache_info() method to see how the cache performs, and you can tune it if needed. In our example, we used an artificially small maxsize to see the effect of elements being removed from the cache:
The following example is somewhat similar to the Registering Plugins example from earlier, in that it does not really change the behavior of the decorated function. Instead, it simply adds unit as a function attribute:
+
defset_unit(unit):
+ """Register a unit on a function"""
+ defdecorator_set_unit(func):
+ func.unit=unit
+ returnfunc
+ returndecorator_set_unit
+
+
The following example calculates the volume of a cylinder based on its radius and height in centimeters:
Units become even more powerful and fun when connected with a library that can convert between units. One such library is pint. With pint installed (pip install Pint), you can for instance convert the volume to cubic inches or gallons:
You could also modify the decorator to return a pintQuantity directly. Such a Quantity is made by multiplying a value with the unit. In pint, units must be looked up in a UnitRegistry. The registry is stored as a function attribute to avoid cluttering the namespace:
+
defuse_unit(unit):
+ """Have a function return a Quantity with given unit"""
+ use_unit.ureg=pint.UnitRegistry()
+ defdecorator_use_unit(func):
+ @functools.wraps(func)
+ defwrapper_use_unit(*args,**kwargs):
+ value=func(*args,**kwargs)
+ returnvalue*use_unit.ureg(unit)
+ returnwrapper_use_unit
+ returndecorator_use_unit
+
+@use_unit("meters per second")
+defaverage_speed(distance,duration):
+ returndistance/duration
+
+
With the @use_unit decorator, converting units is practically effortless:
Here we ensure that the key student_id is part of the request. Although this validation works, it really does not belong in the function itself. Plus, perhaps there are other routes that use the exact same validation. So, let’s keep it DRY and abstract out any unnecessary logic with a decorator. The following @validate_json decorator will do the job:
In the above code, the decorator takes a variable length list as an argument so that we can pass in as many string arguments as necessary, each representing a key used to validate the JSON data:
+
+
The list of keys that must be present in the JSON is given as arguments to the decorator.
+
The wrapper function validates that each expected key is present in the JSON data.
+
+
The route handler can then focus on its real job—updating grades—as it can safely assume that JSON data are valid:
This has been quite a journey! You started this tutorial by looking a little closer at functions, particularly how they can be defined inside other functions and passed around just like any other Python object. Then you learned about decorators and how to write them such that:
+
+
They can be reused.
+
They can decorate functions with arguments and return values.
+
They can use @functools.wraps to look more like the decorated function.
+
+
In the second part of the tutorial, you saw more advanced decorators and learned how to:
+
+
Decorate classes
+
Nest decorators
+
Add arguments to decorators
+
Keep state within decorators
+
Use classes as decorators
+
+
You saw that, to define a decorator, you typically define a function returning a wrapper function. The wrapper function uses *args and **kwargs to pass on arguments to the decorated function. If you want your decorator to also take arguments, you need to nest the wrapper function inside another function. In this case, you usually end up with three return statements.
If you are still looking for more, our book Python Tricks has a section on decorators, as does the Python Cookbook by David Beazley and Brian K. Jones.
+
For a deep dive into the historical discussion on how decorators should be implemented in Python, see PEP 318 as well as the Python Decorator Wiki. More examples of decorators can be found in the Python Decorator Library. The decorator module can simplify creating your own decorators, and its documentation contains further decorator examples.
+
Also, we’ve put together a short & sweet Python decorators cheat sheet for you:
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Decorators 101
+
+
+
+
🐍 Python Tricks 💌
+
+
+
+
+
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
+
+
+
+
+
+
+
+
+
+
+
+
+
About Geir Arne Hjelle
+
+
+
+
+
+
+
+
+
Geir Arne is an avid Pythonista and a member of the Real Python tutorial team.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:
Real Python Comment Policy: The most useful comments are those written with the goal of learning from or helping out other readers—after reading the whole article and all the earlier comments. Complaints and insults generally won’t make the cut here.
+
+
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Comentario del anunciante