Zac*_*c B 3 python metaprogramming decorator self-modifying python-decorators
假设我有一个重复的函数或方法,比如在执行每个操作之前检查一个值,如下所示:
def myfunc():
if mybool:
do_operation_1()
else:
return
if mybool:
do_operation_2()
else:
return
...
Run Code Online (Sandbox Code Playgroud)
这些检查会重复,最终会浪费大量时间和键盘弹簧,特别是在经常需要时.
如果您可以控制操作函数,例如,do_operation_N您可以使用检查布尔值的函数来修饰函数.
但是,如果您无法控制各个do_operation_N操作,该怎么办?如果,对于函数或方法中的每一行,我想要执行相同的检查,是否有某种方法可以"插入"它而无需在每个操作行上明确写入它?例如,是否有一些装饰魔术我可以做以下事情?
def magic_decorator(to_decorate):
def check(*args, **kwargs):
for call in to_decorate: #magic
if mybool:
to_decorate.do_call(call) #magic
else:
return #or break, raise an exception, etc
return check
@magic_decorator
def myfunc():
do_operation_1()
do_operation_2()
...
Run Code Online (Sandbox Code Playgroud)
如果有办法实现这一点,我不在乎它是否使用装饰器; 我只是想用某种方式说"对于函数/方法X中的每一行,先做Y".
do_call上面方法的"神奇"示例是我所追求的简写,但它会遇到单个行的无序执行的严重问题(例如,如果函数的第一行是变量赋值,并且第二个是使用该变量,不按顺序执行它们会导致问题).
要明确:外部控制函数执行的逐行顺序的能力不是我想要实现的:理想情况下,我只是实现一些在自然执行顺序中执行操作的东西每次myfunc都做点什么.如果"做某事"最终被限制为"调用函数或方法"(不包括赋值,if检查等),那很好.
按顺序存储您的操作,然后使用循环:
ops = (do_operation_1, do_operation_2, do_operation_3)
for op in ops:
if mybool:
op()
else:
return
Run Code Online (Sandbox Code Playgroud)