Skip to content

上下文 Manager

一句话解释

上下文 manager 是 对象 那个 manages 设置 and teardown (cleanup) 围绕 块 的 code, used 使用 使用 语句.

用大白话说

上下文 manager handles resource 设置 and cleanup 围绕块 的 code. 你 use 它使用 with 语句: with resource as r: .... The context manager ensures cleanup runs even if an exception occurs.

The most common example is file handling: 使用打开('file') as f: guarantees the file is closed, even if an error occurs inside the block. Without 使用, you'd need try/finally to ensure cleanup.

A context manager implements __enter__ (setup, returns the resource) and __exit__ (cleanup, handles exceptions). You can also create context managers with the @contextmanager decorator from the contextlib module, using a generator function.

示例

python
# Using a built-in context manager
with open("example.txt", "w") as f:
    f.write("Hello")
# File is automatically closed here

# Creating a context manager
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self

    def __exit__(self, *args):
        import time
        self.elapsed = time.time() - self.start
        print(f"Elapsed: {self.elapsed:.4f}s")

with Timer():
    sum(range(1000000))
# Prints: Elapsed: 0.0xxx s

上下文 managers handle 设置/cleanup 使用 使用 语句. __enter__ 设置 上, __exit__ cleans 上.

常见混淆

  • 容易混淆的对象: try/最后

    关键区别: 上下文 manager (使用) and try/最后 两者都 ensure cleanup. 上下文 managers 是 cleaner and 更多 reusable. try/最后 是 更多 explicit 但 verbose. Prefer 使用 for resource management 当 上下文 manager 是 available.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表