- 提醒用户使用了废弃的函数
def deprecated(func):
"""This decorator is used to mark functions as deprecated.
It will result in a warning being emitted when the function is used.
"""
@functools.wraps(func)
def new_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # turn off filter
warnings.warn(
"Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning,
stacklevel=2
)
warnings.simplefilter('default', DeprecationWarning) # reset filter
return func(*args, **kwargs)
return new_func
- 装饰类中函数的装饰器,给函数增加报错功能
# 装饰类中函数的装饰器第一个参数是self
def connection_closed_handler(function):
"""Handle ConnectionClosedException."""
@wraps(function)
def _wrap(inst, *args, **kwargs):
try:
return function(inst, *args, **kwargs)
except (ConnectionClosedException, WebSocketConnectionClosedException):
inst.logger.warn("the connection lost. Resetting ...")
inst.reset(args[1])
return function(inst, *args, **kwargs)
return _wrap