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

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

    Noam, The property of func_code to use is co_name. See below, all that is changed is two lines at top of d()'s def

    def d(f):
       if f.func_code.co_name == 'wrapper':
          return f    #ignore it  (or can throw exception instead...)
       @wraps(f)
       def wrapper(*args, **kwargs):
          print 'calling func'
          return f(*args, **kwargs)
       return wrapper
    

    Also, see for Lukáš Lalinský's approach which uses a explicitly defined property attached to the function object. This may be preferable as the "wrapper" name may be used elsewhere...

提交回复
热议问题