Decorators in Python

 

Why Do You Need Decorators?


If there is any behavior that is common to more than one function, you probably need to make a decorator.

Examples:
Checking argument type at runtime
Benchmark function calls
Cache function results
Count function calls
Checking metadata (permissions, roles, etc.)
Metaprogramming
And much more…

Decorators With Return Values
Suppose we want to know how long each function call takes. Also, functions return something most of the time, so the decorator must handle that as well:

def timer_decorator(func):
  def timer_wrapper(*args, **kwargs):
    import datetime                 
    before = datetime.datetime.now()                     
    result = func(*args,**kwargs)                
    after = datetime.datetime.now()                      
    print "Elapsed Time = {0}".format(after-before)      
    return result
    
@timer_decorator
def sum(x, y):
  print(x + y)
  return x + y
  
sum(2, 5)
> 7
> Elapsed Time = some time

Decorators With Arguments
Sometimes, we want a decorator that accepts values (like @app.route('/login') in Flask):



Comments

Popular posts from this blog

Read and Navigate XML - Beautiful Soup

difference-between-stream-processing-and-message-processing

WordNet in Python