Code Candy 2: Learning about Decorators in Python

Anindita Sengupta
Analytics Vidhya
Published in
3 min readMar 12, 2019

While working on huge projects haven’t you seen some code which is just inches away from doing what you’d like it to do and you think, if only this function would tie up the loose ends so as to fit for my application, if only I could tweak this existing function.

Python comes to our rescue by offering a special functionality to reuse and extend the functions. You can take an existing piece of code thats working perfectly and add your flourishes to it.This is an example of meta programming as a part of existing program.

How does Python do this?

Python treats everything as an object classes, data and functions. Functions are simple objects with attributes . Different names can be associated with same function, function can be returned from functions and even passed as argument .

What a decorator does is take a function as an argument and add some more features and returns it. This could be useful in extending existing functionalities to meet new requirements or cater to a new interface.

Code for defining a Decorator

It’s simple to define a decorator, as a function which will take a function as an argument, and within its body add some more feature to it. Please see the below python snapshot for the task that needs to be done.

Calling a Decorator

Here is how a decorator gets called. Since the decorator returns a function, it gets assigned to b which is again a function and needs to be called with parentheses after it to execute the code . Just typing print(b) will give the address of the function and will not execute the decorator.

And the below is the output

Another way to invoke the decorator generating the same output as above would be this.

Caution while using a decorator

It’s important to keep the entire system design in mind while defining a decorator, deeply nested and wrapped functions may cause system to slow down,also Python 2.3 and earlier versions wouldn’t support this feature.

Pop this code candy in your mind to get a taste of decorators.. and inch closer to code enlightenment.

Hope you can use this to design better code! Happy Coding!

--

--