Python has an intriguing feature called decorators that allows you to add functionality to existing programs. This is also known as metaprogramming since a portion of the program attempts to alter another portion of the program during the compilation process. Learning requirements for decorators: To comprehend decorators, we must first grasp a few fundamental Python concepts.
We must be comfortable with the reality that everything in Python is an object (yes, including classes). The names we provide to these things are merely identifiers. Functions are not exceptions; they are also objects (with attributes). Different names can be assigned to the same function object.
def function(value): print(value) function("Enablegeek") second = function second("Enablegeek")
The output from the first and second functions is the same when the code is executed. The first and second names in this case correspond to a similar function object. Things are starting to become strange now. Functions can be provided to another function as parameters. If you’ve used Python functions like map, filter, or reduce, you’re already aware of this. Higher-order functions are functions that accept other functions as parameters. Here’s an example of a function like this.
def additive(item): return item + 10 def substructive(item): return item - 10 def operator(func, x): result = func(x) return result print(operator(additive, 100)) print(operator(substructive, 100))
Returning to Decorators, Callable functions and methods are those that can be called. Callable refers to any object that implements the special call() function. A decorator, in the most basic sense, is a callable that returns another callable. A decorator basically takes a function, adds some functionality to it, and returns it.
def decorated_function(func): def internal(): print("Decorated methods here!") func() return internal def simple_function(): print("Ordinary methods here!") simple_function() well_decorated = decorated_function(simple_function) well_decorated()
Ordinary methods here! Decorated methods here! Ordinary methods here!
The function Simple_Fuction() was decorated, and the resulting function was named Well_Decorated().
The decorator function, as we can see, provided some extra functionality to the original function. This is analogous to wrapping a present. The decorator serves as a container. The nature of the adorned object (the real present within) remains unchanged. However, it now appears to be attractive (since it got decorated).
In general, we decorate a function and rename it,
def decorated_function(func): def internal(): print("Decorated methods here!") func() return internal @decorated_fFunction def simple_function(): print("Ordinary methods here!") simple_function()
Decorated methods here! Ordinary methods here!
Python Decorator Chaining
Python allows for the chaining of several decorators. This means that a function can be decorated several times with various (or the same) decorators. The decorators are simply placed above the required function.
def initialize(func): def internal(*args, **kwargs): print("$" * 30) func(*args, **kwargs) print("$" * 30) return internal def hash_wise(func): def internal(*args, **kwargs): print("#" * 30) func(*args, **kwargs) print("#" * 30) return internal @initialize @hash_wise def printer(msg): print(msg) printer("Enablegeek is Awesome!")
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ ############################## Enablegeek is Awesome! ############################## $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
This has been a long road! You began this session by learning more about functions, specifically how they may be defined inside other functions and handed around like any other Python object. Then you discovered decorators and how to write them.
Decorators in Python are a powerful feature that allows programmers to modify the behavior of functions or classes. Decorators are functions that take a function as input and return a new function with some added functionality. This can be useful for adding additional checks or functionality to a function without modifying the original code.
Decorators can be used to simplify code, as they allow you to define reusable functionality in a single place and apply it to multiple functions. This can make code easier to read, maintain, and update, as you can make changes in one place and have those changes automatically applied to all of the functions that use the decorator.
Decorators are commonly used for tasks such as logging, timing, caching, or authentication. By using decorators, you can keep the core logic of your functions clean and focused on their main task, while adding additional functionality through the decorator.
Decorators are an important feature of Python that allows for flexible and reusable code, making it easier to write, read, and maintain complex applications.