有没有办法直接"装饰"一段Python代码?

Pau*_*gel 5 python python-decorators

我有一堆代码:

statement1(args)
statement2(args)
statement3(args)
statement4(args)
statement5(args)
Run Code Online (Sandbox Code Playgroud)

我想将语句分成块并在每个块之后写入日志.日志记录有点复杂:我想记录块执行后的每个块的运行时间和特定数据结构的状态.所以我创建了一个名为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()
Run Code Online (Sandbox Code Playgroud)

这很好用,但它有点笨重.令人讨厌的是我必须单独调用三个块函数,如果我想在块之间共享变量,那么我要么必须给出块函数参数和返回语句,要么使用全局变量,这两者都不是特别适合.我真正想要的是这样的语法:

@log_block()
    statement1(args)
    statement2(args)

@log_block()
    statement3(args)

@log_block()
    statement4(args)
    statement5(args)
Run Code Online (Sandbox Code Playgroud)

所以我直接装饰语句而不是将它们包含在辅助块函数中.有没有办法实现这样的事情?

Dan*_*man 5

上下文管理器正是您正在寻找的.您可以将它们与with语句一起使用,并定义在进入和退出with块时运行的代码.