"with" 语句中的变量范围?

Scope of variable within "with" statement?

我只阅读 python 中的 firstline 使用 :

with open(file_path, 'r') as f:
    my_count = f.readline()
print(my_count)

我对变量的范围有点困惑 my_count。尽管打印效果很好,但最好先在语句外做 my_count = 0 之类的事情(例如,在 C 中用来做 int my_count = 0

with 语句 不创建范围 (像 ifforwhile 不创建范围范围之一)。

因此,Python 将分析代码并发现您在 with 语句中进行了赋值,因此这将使变量成为局部变量(在实际范围内)。

在Python变量不需要初始化所有代码路径:作为程序员,你有责任使确保在使用变量之前对其进行赋值。这会导致代码更短:例如,您确定一个列表至少包含一个元素,然后您可以在 for 循环中赋值。在 Java 中,for 循环中的赋值被认为是不安全的(因为循环体可能永远不会执行)。

在之前初始化with范围可以更安全,因为在with语句之后我们可以安全地假设变量存在。另一方面,如果变量 应该 with 语句中赋值,在 with 语句之前不初始化它实际上会导致额外的检查:Python 如果在 with 语句中以某种方式跳过赋值,将会出错。

with 语句仅用于上下文管理目的。它强制(通过语法)您在 with 中打开的上下文在缩进结束时关闭。

您还应该阅读 PEP-343 和 Python Documentation. It will clear that its not about creating scope its about using Context Manager。我正在引用 python 有关上下文管理器的文档

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.