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

后端 未结 4 2021
既然无缘
既然无缘 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:27

    I'd store the information in the function itself. There is a risk of a conflict if multiple decorators decide to use the same variable, but if it's only your own code, you should be able to avoid it.

    def d(f):
        if getattr(f, '_decorated_with_d', False):
            raise SomeException('Already decorated')
        @wraps(f)
        def wrapper(*args,**kwargs):
            print 'Calling func'
            return f(*args,**kwargs)
        wrapper._decorated_with_d = True
        return wrapper
    

    Another option can be this:

    def d(f):
        decorated_with = getattr(f, '_decorated_with', set())
        if d in decorated_with:
            raise SomeException('Already decorated')
        @wraps(f)
        def wrapper(*args,**kwargs):
            print 'Calling func'
            return f(*args,**kwargs)
        decorated_with.add(d)
        wrapper._decorated_with = decorated_with
        return wrapper
    

    This assumes that you control all the decorators used. If there is a decorator that doesn't copy the _decorated_with attribute, you will not know what is it decorated with.

提交回复
热议问题