A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods.
Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.
你也应该通过PEP-343和Python Documentation。很明显,它不是关于创建范围,而是关于使用Context Manager。我引用了上下文管理器上的python文档
with
语句不创建作用域(如if
,for
和while
也不创建作用域)因此,Python将分析代码,并看到您在
with
语句中进行了赋值,从而使变量成为局部变量(到实际范围)在Python中,变量不需要初始化在所有代码路径中:作为程序员,您有责任确保在使用变量之前对其进行赋值。这可能会导致代码更短:例如,您确信一个列表至少包含一个元素,然后您可以在
for
循环中赋值。在Java中,for
循环中的赋值被认为是不安全的(因为循环体可能永远不会执行)初始化在之前
with
范围可以更安全,因为在with
语句之后,我们可以安全地假设变量存在。另一方面,如果变量应该在with
语句中赋值,在with
语句之前不初始化它实际上会导致额外的检查:如果在with
语句中以某种方式跳过赋值,Python将出错with语句仅用于上下文管理目的。它强制(通过语法)在缩进结束时关闭在
with
中打开的上下文相关问题 更多 >
编程相关推荐