Functions

&

Decorators

Choudhary Sourya Vatsyayan

Programmer @ DoSelect

What's This Talk About?

 - Functions and scopes

 - What a decorator is

 - Constructing a decorator

 - Why use a decorator

 - Every function has a new namespace

 - Resolution is local-first and then enclosing namespaces

y = 2

def f():

       x = 1

def g():

       print y # prints 2

       print x # error

 

 - We can define a function inside another function

 - Functions are objects, too

        def f():

               print "yello"

         g = f

         g() # prints yello

 - We can pass functions as parameters

 

def f(a, b):

       print a + b

 

def g(func):

       func(1, 2) # calls the function passed

 

g(f) # prints 3

def f(func):

       return func

 

def g(a, b):

       print a + b

 

f(g)(1, 2) # prints 3

def f(func):

       def wrapper(*args, **kwargs):

              print "Before"

              ret = func(*args, **kwargs)

              print "After"

              return ret

        return wrapper

 

def g(a, b):

       print a + b

 

f(g)(1, 2)

@f

def g(a, b):

       print a + b

 

g(1, 2)

# prints Before

# prints 3

# prints After

d = f(g)

d.__name__ # prints 'wrapper'

 

#Use functools.wraps

def f(func):

       @functools.wraps(func)

       def wrapper(*args, **kwargs):

              # some more code

              return func(*args, **kwargs)

        return wrapper

d = f(g)

d.__name__ # prints 'g'

Why Use Decorators

 

 - Simplifies logic addition

 - No repetition required

 - Life is easier

 

Decorators With Arguments

@decorator("my_message")

def f():

       print "Yello"

 

# prints "my_message"

# prints "Yello"

def f(msg):

       def inner(func):

              @functools.wraps(func)

              def w(*args, **kwargs):

                     print msg

                     return func(*args, **kwargs)

              return w

         return inner

Uses

 - Logging

 - Authentication

 - Timing code

Thanks!

 

Questions?

Made with Slides.com