Prevent decorator from being used twice on the same function in python

后端 未结 4 2022
既然无缘
既然无缘 2020-12-20 07:42

I have a decorator:

from functools import wraps
def d(f):
    @wraps(f)
    def wrapper(*args,**kwargs):
        print \'Calling func\'
        return f(*arg         


        
4条回答
  •  眼角桃花
    2020-12-20 08:25

    I'll also propose my solution:

    first, create another decorator:

    class DecorateOnce(object):
        def __init__(self,f):
            self.__f=f
            self.__called={} #save all functions that have been decorated 
        def __call__(self,toDecorate):
            #get the distinct func name
            funcName=toDecorate.__module__+toDecorate.func_name
            if funcName in self.__called:
                raise Exception('function already decorated by this decorator')
            self.__called[funcName]=1
            print funcName
            return self.__f(toDecorate)
    

    Now every decorator you decorate with this decorator, will restrict itself to decorate a func only once:

    @DecorateOnce
    def decorate(f):
        def wrapper...
    

提交回复
热议问题