【发布时间】:2020-05-23 01:46:51
【问题描述】:
对于装饰器来说还很陌生,这会被认为是糟糕的代码吗?如果是,什么是好的替代品?
import functools
def error_handaler_decorator(func):
@functools.wraps(func)
def wrapper(error_message_for_wrapper = None, cont = True, *args, **kwargs):
try:
return func(*args, **kwargs)
except:
if error_message_for_wraper != None:
# Report error to user in application specific way
if cont == True:
return True
@error_handaler_decorator
def some_func(input_for_func):
# Do a thing.
@error_handaler_decorator
def some_func_in_a_class(self,input):
# Do another thing.
some_func(error_message_for_wrapper = something bad happened, input_for_func = some_input)
some_class.some_func_in_a_class(error_message_for_wrapper = something bad happened, cont = False, input_for_func = some_input)
这意味着我在调用装饰函数时必须传递包装器变量,我认为我不能传递args,只能传递kwargs,但它允许我根据什么来定义错误消息我传递给函数,而不是在我定义函数时。
代码有效,(至少与我测试过的一样),但我的 IDE(Visual Studio 代码)非常生气,说:
方法调用中出现意外的关键字参数“error_message_for_wrapper”
我真的很想清理我的代码,我看到的替代方案是try: except: 或with:。 try: except: 让我的代码变得混乱,(至少主观上是这样)。
With. 更好,但我宁愿将我的装饰器作为函数,它更适合项目。
我认为我不能将 with 作为函数。
【问题讨论】:
-
VSCode 正在做静态分析;它不会跟踪代码的(未来)执行以发现
some_func,它被静态绑定到具有一个参数的函数,动态地反弹到一个完全不同的签名函数。