Python: General decorator

General decorator, that can be used to class method and function (keyword args are also permitted) by checking whether args[0] is ‘self’ or not and kwargs.

# -*- coding:utf-8 -*-
import inspect
def multiply(func):
    def _multiply(*args, **kwargs):
        if inspect.getargspec(func).args[0] == 'self':
            # 'if inspect.ismethod(func):' doesn't work in this situation,
            # because when decorating the method isn't bounded to its class yet.
            return func(*args, **kwargs) * (kwargs['num'] if 'num' in kwargs else args[1])
            return func(*args, **kwargs) * (kwargs['num'] if 'num' in kwargs else args[0])
    return _multiply
def func(num):
    return num 
class Calc(object):
    def method(self, num):
        return num 
# method, function or kwargs can be used. 
c = Calc()
print c.method(2)
# 4
print c.method(num=10)
# 100
print func(5)
# 25
print func(num=20)
# 400

Leave a Reply

Your email address will not be published. Required fields are marked *