Python 在块之前和之后运行一些公共代码
在当前的项目中,我发现自己经常编写这样的代码:Python 在块之前和之后运行一些公共代码,python,python-3.x,Python,Python 3.x,在当前的项目中,我发现自己经常编写这样的代码: statement_x() do_something() do_other_thing() statement_y() # ... statement_x() do_third_thing() do_fourth_thing() statement_y() 正如您所看到的,statement\u x和statement\u y经常重复,而且它们总是成对出现,但我无法将它们压缩成一条语句。我真正想要的是这样一种语言结构: def env
statement_x()
do_something()
do_other_thing()
statement_y()
# ...
statement_x()
do_third_thing()
do_fourth_thing()
statement_y()
正如您所看到的,statement\u x
和statement\u y
经常重复,而且它们总是成对出现,但我无法将它们压缩成一条语句。我真正想要的是这样一种语言结构:
def env wrapping:
statement_x()
run_code
statement_y()
在本例中,我假设env
是一个Python关键字,表示在给定块前后运行某些语句的特殊“三明治函数”,块的入口点由第二个关键字run\u code
表示
使用此结构,我的上述程序现在更具可读性:
env wrapping:
do_something()
do_other_thing()
env wrapping:
do_third_thing()
do_fourth_thing()
我的意思是有完全相同的行为
据我所知,这样的构造并不存在,我的问题的重点不是猜测Python未来的特性。然而,这种“在变量块之前和之后运行一些公共代码”的情况肯定会经常发生,以至于Python有一种方便的方法来处理它!这边是什么?或者说,Pythonic的解决方案就是简单地放弃并接受重复 PS:我意识到我可以编写一个将变量语句作为参数的函数,但这对用户来说不是很友好-我最终会在函数的参数中编写大量语句列表。你可以使用 示例使用: 用法示例:
>>> with doing_xy():
... print('do_something')
... print('do_other_thing')
...
statement_x
do_something
do_other_thing
statement_y
>>> with doing_xy():
... print('do_third_thing')
... print('do_fourth_thing')
...
statement_x
do_third_thing
do_fourth_thing
statement_y
with
语句的另一个好处是,即使代码块引发异常,语句也会在代码块运行后运行位。@Blckknght,要做到这一点,产生
语句,其余的应该用try.保护。。最后…
。啊,是的,我应该说:“它允许您运行语句,即使引发了异常”。您确实需要做一些工作来启用它。
>>> with doing_xy():
... print('do_something')
... print('do_other_thing')
...
statement_x
do_something
do_other_thing
statement_y
>>> with doing_xy():
... print('do_third_thing')
... print('do_fourth_thing')
...
statement_x
do_third_thing
do_fourth_thing
statement_y