简体   繁体   English

Python:为什么在装饰器中使用包装器?

[英]python: why use a wrapper in decorator?

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

the code is in whoosh/src/util.py,I can't understand the synchronized_wrapper's effect and the parameters in synchronized_wrapper(self, *args, **kwargs) from where. 该代码在whoosh / src / util.py中,我从哪里无法理解synced_wrapper的效果和synced_wrapper(self,* args,** kwargs)中的参数。 Can anyone give me some pointers? 谁能给我一些指导?

The @wraps decorator is just syntactic sugar for a function closure with argument forwarding. @wraps装饰器只是用于使用参数转发关闭函数的语法糖。 *args refers to a tuple of positional args, and **kwargs refers to a dict of all keyword args that have been passed to func . *args表示位置args的元组,而**kwargs表示已传递给func的所有关键字args的字典。

Hence if you had: 因此,如果您有:

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

and did: 并做了:

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

it would basically be like calling: 它基本上就像调用:

f(a, bar=z)

but inside the " with self._sync_lock: " context manager 但在“ with self._sync_lock: ”上下文管理器中

Decorating a function causes problems with reflection-based operations, and @wraps is designed to make the wrapped function truly simulate the original function. 装饰一个函数会导致基于反射的操作出现问题,并且@wraps旨在使包装后的函数真正模拟原始函数。 The link lucemia provided has applicable info. 提供的链接 lucemia具有适用的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM