[컴][파이썬] python decorator

python annotation / python anno / python decoration / python decorator


참고 : Python Decorators II: Decorator Arguments

Python decorator 예제

@fixme

# -*- coding: utf-8 -*-

import warning


def fixme(func, *args, **kwargs):
    def new_func(func, self, *args):
        warning.warn("func.__name__" + args[0]



@sync_hitcount : decorator 에 param 이 없는 경우
def sync_hitcount(func):
    """
    Decorator sync_hitcount
    decorator to lock the Remittance update to synchronization
    """
    def lock(token):
        """
        _lock is needed during determinination of the remit status.
        Without it, status could not determined appropriately.
        """
        ret = Remittance.objects.updateHitCount(token)
        if ret['status'] == Remittance.STATUS['done_remit']:
            raise ExpiredRemitException("remit has been done")
        if ret['hit_count'] > 1:
            raise RemitIsLockedException("on remitting")

    def unlock(remitInfo):
        # init hit_count
        remitInfo.hit_count = 0
        remitInfo.save()

    def dec(*args, **kwargs):

        try:
            lock(kwargs['token'])
            func(*args, **kwargs)
        finally:
            unlock(kwargs['remitInfo'])

        return

    return dec

@iframe : : decorator 에 param 이 있는 경우
def iframe(iframe_param):
    def dec(func):
        def dec_dec(*args, **kwargs):
            func(*args, **kwargs)
            return
            
        return dec_dec
    return dec

@iframe : : decorator 에 param 이 있는 경우, class method 에 적용하는 경우
def decorator(iframe_param):
    def dec(func):
        def dec_dec(self, *args, **kwargs):
            func(self, *args, **kwargs)
            return
            
        return dec_dec
    return dec

댓글 없음:

댓글 쓰기