[英]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:
”上下文管理器中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.