我有一堆代码:
statement1(args)
statement2(args)
statement3(args)
statement4(args)
statement5(args)
我想将语句分成 block 并在每个 block 之后写入日志。日志记录有点复杂:我想记录每个 block 的运行时间和 block 执行后特定数据结构的状态。所以我创建了一个名为 log_block
的装饰器来处理所有这些细节。现在我的代码如下所示:
@log_block()
def block1():
statement1(args)
statement2(args)
@log_block()
def block2()
statement3(args)
@log_block()
def block3():
statement4(args)
statement5(args)
block1()
block2()
block3()
这工作得很好,但有点笨拙。令人恼火的是,我必须分别调用三个 block 函数,如果我想在 block 之间共享一个变量,那么我要么必须为 block 函数提供参数和返回语句,要么使用全局变量,这两者都不是特别可口。我真正想要的是这样的语法:
@log_block()
statement1(args)
statement2(args)
@log_block()
statement3(args)
@log_block()
statement4(args)
statement5(args)
这样我就可以直接修饰语句而不是将它们封装在辅助 block 函数中。有什么办法可以实现这样的目标吗?
最佳答案
Context managers正是您要寻找的。您将它们与 with
语句一起使用,它们定义了在进入和退出 with block 时运行的代码。
关于python - 有没有办法直接 "decorate"一段Python代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38439105/