Tuesday, October 20, 2015

Understanding python decorator in easy way

I still have enough energy to write something on my blog :D after one week trip to Jakarta for some work reason. I am so tired but I want to write and share something about python decorator before I sleep :-).

Lets see how python function work,

Code 1:
def myfunc(a):
    print(a)

decorator = myfunc
decorator('It\'s Works')
Output 1:
It's Works

Code 2:
def myfunc(*args):
    print(args)

decorator = myfunc
decorator('It\'s', 'Works', 'Yeah', 'Must be ok')
Output 2:
("It's", 'Works', 'Yeah', 'Must be ok')

Code 3:
def myfunc(**kwargs):
     print(kwargs)

decorator = myfunc
decorator(a=1, b=2, c=3)
Output 3:
{'a':1, 'b':2, 'c':3}

Inner Function
Inner function is function inside function or we can call it nested function. Look at code bellow:
def myfunc(a):
    def inner_myfunc():
        print(a)

    return a

decorator = myfunc
decorator('inner myfunc')
Output should be:
'inner myfunc'
from the code we can se that, argument or parameter a is accessible from inner function.

I have some question why I always wrote decorator = myfunc? I just want to show python function can be assigned to var as alias or pointer.

@some_decorator
def myfunc():
    return a

it's mean:
myfunc = some_decorator(myfunc)

Lets try to the real code with decorator implementation:

# define logger function
# we will this for as decorator
def logger(func):
    def inner(*args, **kwargs): #1
        print "Arguments were: %s, %s" % (args, kwargs)
        return func(*args, **kwargs) #2
       
    return inner

# use the decorator
@logger
def myfunc1(x, y=1):
    return x * y

# use the decorator
@logger
def myfunc2():
    return 2

After define function now try to call myfunc1 and myfunc2:

# call function
myfunc1(5, 4)

# output should be
Arguments were: (5, 4), {}
20

# call function
myfunc1(1)

# output should be
Arguments were: (1,), {}
1

# call function
myfunc2()

# output should be
Arguments were: (), {}
2

If you need more explanation you can comment this post, just comment and I will try to answer :-).

Let Sleep.....

No comments:

Post a Comment