【问题标题】:python: why use a wrapper in decorator?python:为什么在装饰器中使用包装器?
【发布时间】:2012-12-12 02:13:29
【问题描述】:
def synchronized(func):
    """Decorator for storage-access methods, which synchronizes on a threading
    lock. The parent object must have 'is_closed' and '_sync_lock' attributes.
    """

    @wraps(func)
    def synchronized_wrapper(self, *args, **kwargs):
        with self._sync_lock:
           return func(self, *args, **kwargs)

    return synchronized_wrapper

代码在 whoosh/src/util.py 中,我无法理解 synchronized_wrapper 的作用和 synchronized_wrapper(self, *args, **kwargs) 中的参数从哪里来。谁能指点一下?

【问题讨论】:

标签: python decorator


【解决方案1】:

@wraps 装饰器只是带有参数转发的函数闭包的语法糖。 *args 指的是位置参数元组,**kwargs 指的是已传递给func 的所有关键字参数的字典。

因此,如果你有:

def f(foo, bar=None):
    ...

并且做到了:

sync_f = someinst.synchronized(f)
sync_f(a, bar=z)

基本上就像调用:

f(a, bar=z)

但在“with self._sync_lock:”上下文管理器中

【讨论】:

    【解决方案2】:

    装饰函数会导致基于反射的操作出现问题,@wraps 旨在使包装函数真正模拟原始函数。 The linklucemia 提供了适用的信息。

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 2011-08-11
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 2020-06-29
      • 2018-11-20
      • 2018-02-19
      相关资源
      最近更新 更多