【问题标题】:Why variable is optional in a with statement? [duplicate]为什么变量在 with 语句中是可选的? [复制]
【发布时间】:2015-02-26 16:00:19
【问题描述】:

最近学习了python中的'with'语句及其用法,主要来自Understanding Python's "with" statementofficial documentation for with statement这一篇文章。

最常用的例子我可以理解

with open("x.txt") as f:
    data = f.read()
    do something with data

好的,所以我们打开文件x.txt,我们用它执行一些任务,它会自动关闭。 f 变量用于读取文件并执行其他任务。

但在官方文档中,表达式后面的目标变量是可选的:

with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]

我没有找到任何在没有目标变量的情况下使用 with 语句的示例。是否存在不需要此变量的情况?

【问题讨论】:

  • multiprocessing.Lock 是一个例子eli.thegreenplace.net/2012/01/04/…
  • 轶事:我曾经写过一个with silenced_output(): 语句,它将所有stdout 消息重定向到dev/null。 with silenced_output() as x: 没有多大意义,因为我不需要对 x 做任何事情。
  • 好吧,我没有注意到这个问题已经回答了here。对此感到抱歉

标签: python with-statement


【解决方案1】:

是的,你可以在这个答案中找到其中的几个:What is the python "with" statement designed for?

我能想到的最直接的就是线程锁了(上个链接也列出来了):

lock = threading.Lock()
with lock:
    # Critical section of code

为了记录,我还要引用the with doc

with 语句用于用方法 [...] 包装块的执行。这允许封装常见的 try...except...finally 使用模式,以便于重用。

由于您在try...except...finally 中并不总是需要一个变量,因此您在with 语句中并不绝对需要一个目标变量。

【讨论】:

    【解决方案2】:
    from threading import Lock
    
    lock = Lock()
    
    with lock:
        # access critical data
    
    # continue
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      相关资源
      最近更新 更多