Python Tutorial

Showing posts with label decorator. Show all posts
Showing posts with label decorator. Show all posts

Tuesday, February 19, 2013

Decorator in python

Python decorator example : Validate a function argument using decorator.


All source code available on github
from functools import wraps

def validate(func):
    @wraps(func)
    def wrapper(*args):
        for num in args:
            try:
                int(num)
            except:
                return None
        return func(*args)

    return wrapper

@validate
def add_num(*args):
    total = 0
    for num in args:
        total += num
    return total


print add_num(1,2,3)
print add_num(1,2,"asd")
print add_num(1,2,None)


Output:
6
None
None

Python implement caching - using decorator

Python custom caching using decorator.

All source code available on github

from functools import wraps

def custom_memoize(func):
    cache = {}
    @wraps(func)
    def wrapper(*args):
        if args in cache:
            print "Returning cache data"
            return cache[args]
        # If result not found then call the function
        result = func(*args)
        cache[args] = result
        return result

    return wrapper

@custom_memoize
def add(x,y):
    return x+y

print add(1,2)
print add(2,5)
print add(1,2)
print add(2,5)

Output:
3
7
Returning cache data
3
Returning cache data
7