Decorators! in Python !

Hey Friends,

Let me help you with that crazy piece of code that deals with decorators !
So what is it ?

Do you remember the ‘@’ symbol above the function? Why did the programmer even use it ? First is first, what do you even call it ? Annotation? Here you can call it PIE!

In a sentence, a decorator in python is a function that decorates another function! I swear, if it was not important I would not have bothered to write a blog post on it. It IS IMPORTANT when you move to higher order development like using Django, Flask or anything cute.

Basics first :
A function is a first class object in Python. This basically means that you can use it as object variables all over your code like passing it as arguments, assignment etc. If I am not wrong it is the case for JavaScript too. Have you ever used callbacks ? If not you should and then you will know the power of this particular feature.

def myFunc():
print 'Hey, it\'s me myFunc!!'
x = myFunc
x()

Do yo know what it will do? Yes, it will print whatever is inside myFunc for it is the same as myFunc now.

Now, see this piece of code :
def decoratorFunc(someFunc):
def wrapper():
print 'I am before someFunc'
someFunc()
print 'I am after someFunc'
return wrapper

# BREAK
myFunc = decoratorFunc(myFunc)
myFunc()

I am before someFunc
Hey, it’s me myFunc!!
I am after someFunc

So, the middle line has been decorated with a line above and a line below. The two decorating lines come from the decorator function, here which is decoratorFunc.

Observe the last code statements again.

myFunc = decoratorFunc(myFunc)
myFunc()

These could be rewritten with some syntactical sugar as :
@decoratorFunc
def myFunc():
print 'Hey, it\'s me myFunc!!'

That’s it !!!

Hehe, and yes, you know a little more now. 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s