python - 有没有办法直接 "decorate"一段Python代码?

标签 python python-decorators

我有一堆代码:

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/

相关文章:

python - 使用pyserial读取多个串行设备时延迟较大

python - Beautiful Soup - 任何指定的编码都会破坏美化格式

python decorator TypeError 缺少 1 个必需的位置参数

python - mypy:无类型装饰器使函数 "my_method"无类型

python - 使用 PyInstaller 时出错

python - 使用破折号回调生成多个图

python - Google App Engine Python - Protorpc && 任务队列

Python装饰器添加类级变量

python - 如何在 Python 3 的方法装饰器中调用 super ?

在加载/导入时执行的 Python 装饰器