为什么变量在 with 语句中是可选的?
Why variable is optional in a with statement?
最近学习了python中的'with'语句及其用法,主要来自文章Understanding Python's "with" statement and the official 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 语句示例。是否存在不需要此变量的情况?
from threading import Lock
lock = Lock()
with lock:
# access critical data
# continue
希望对您有所帮助。
是的,您可以在这个答案中找到几个:What is the python "with" statement designed for?
我能想到的最直接的就是线程锁(也列在前面link):
lock = threading.Lock()
with lock:
# Critical section of code
郑重声明,我还要引用 the with
doc :
The with statement is used to wrap the execution of a block with methods [...]. This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.
因为您并不总是需要 try...except...finally
中的变量,所以您在 with
语句中不一定需要目标变量。
最近学习了python中的'with'语句及其用法,主要来自文章Understanding Python's "with" statement and the official 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 语句示例。是否存在不需要此变量的情况?
from threading import Lock
lock = Lock()
with lock:
# access critical data
# continue
希望对您有所帮助。
是的,您可以在这个答案中找到几个:What is the python "with" statement designed for?
我能想到的最直接的就是线程锁(也列在前面link):
lock = threading.Lock()
with lock:
# Critical section of code
郑重声明,我还要引用 the with
doc :
The with statement is used to wrap the execution of a block with methods [...]. This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.
因为您并不总是需要 try...except...finally
中的变量,所以您在 with
语句中不一定需要目标变量。