Decorators — The way life gets simpler!

Recently I was working on a module in a project that had a certain check to be performed each time I interacted with the UI.

The most simple thing I could have done was to create a proper function that returned me the result of this interaction or create a simple lambda. Both the cases beat the purpose of this beautiful language. Hence, I decided it is about time that I venture into something that makes it looks more Python-ic if you may. I used decorators.

Decorators at their very heart are objects which consume objects and return objects. These objects could be anything. In my case, a WebElement. It returns me a plethora of objects (I created more than one decorator) like, boolean, strings, the list goes on.

Enough speaking, now the code.

from functools import wraps 
def wrapper(f): 
@wraps(f):
def wrapping(*args):
....
....
....
return some_value # This return is the heart and soul of
# your decorator
return wrapping
@wrapper 
def my_weak_function(*args, **kwargs):
....
....
....
return awesome_results

In the code above, the,

return some_value

is what provides that extra power to my_weak_function()‘s punch!

My problem was something else, I had to declare a wrapper for a class. And how did I do that?

def awesome_wrapper(func): 
def awesome_power(self):
....
....
....
return func(self)
return awesome_power
class Dummy(object): 
def __init__(self):
....
....
....
    @awesome_wrapper 
def non_awesome_function(self):
....
....
....

Here, what is important is the part,

return func(self)

This guarantees that the function on which the decorator was applied is executed. Passing self might be an eye-sore, but it’s the way to assure the unbound methods get the necessary class instances to work with.

Hope you use decorators in your next modules, and moreover, they look bloody good ;)

For further reading, refer:

[1] http://www.jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/

[2] http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/


Originally published at datqaguy.wordpress.com on October 7, 2015.