What is a Python Decorator
Essentially, Python Decorator is a type of Python function.
A Python decorator enables additional features without changing the original function codes.
With a decorator, we may extract codes not irrelevant to the original functions and add flexibility.
Common decorators are:
- internal decorator
- class decorator
- function decorator
- function decorator with args
Function Decorator
For example, to add a logging feature to a function
Not so smart way
def foo(): |
Here print out foo is not reusable.
Calling an External Function
We can build an external function and call it within foo
def use_logger(func_name): |
But this method, an argument “foo” is still passed.
Decorator
Can build a wrapper method in the function
|
The output would be
foo is running |
More commonly, decorator is used like this:
|
The results:
bar is running |
Function Decorator with Parameters
It’s actually not that different from the function decorator without parameters.
def use_logger(level="debug"): |
The output will be
task bar is running |
Downside of Using Decorators
- The disadvantages of decorators is lack of original function’s info e.g. doctring, __name__, parameter list etc.
def use_logger(level="debug"): |
the output is below
task bar is running |
The name printed is wrapper but what we actually want is bar. One solution is to rewrite the function as below
from functools import wraps |
Let’s run
print(bar.__name__) |
The output will be
bar |
Class Decorator
- Class Decorators can use __call__ method, when @ is applied on functions, this method will be invoked
class Foo: |
The output will be
Class decorator running |
Internal Decorator
Some internal decorators can be used to restrict a value range, e.g.
class Student: |
The output will look like:
4.0 |