考虑以下示例:
with open('a.txt') as f:
pass
# Is f supposed to be defined here?我已经阅读了with-statement的语言文档(2.7)以及PEP-343,但据我所知,他们没有关于这个问题的任何内容。
在CPython 2.6.5中,f似乎是在with-块之外定义的,但我不希望依赖于可能发生变化的实现细节。
发布于 2011-06-22 07:23:21
是的,上下文管理器将在with语句之外可用,并且不依赖于实现或版本。with语句不会创建新的执行范围。
发布于 2011-06-22 05:50:25
with语法:
with foo as bar:
baz()糖大约是用来:
try:
bar = foo.__enter__()
baz()
finally:
if foo.__exit__(*sys.exc_info()) and sys.exc_info():
raise这通常很有用。例如
import threading
with threading.Lock() as myLock:
frob()
with myLock:
frob_some_more()上下文管理器可以不止一次地被使用。
发布于 2011-06-22 05:49:41
如果f是一个文件,它将在with语句之外显示为已关闭。
例如,如下所示
f = 42
print f
with open('6432134.py') as f:
print f
print f将打印:
42
<open file '6432134.py', mode 'r' at 0x10050fb70>
<closed file '6432134.py', mode 'r' at 0x10050fb70>您可以在PEP-0343中的规范部分中找到详细信息:“with”语句。Python scope rules (可能是irritating)也适用于f。
https://stackoverflow.com/questions/6432355
复制相似问题