刘心向学(42):上下文管理器(Context Managers)

B站影视 欧美电影 2025-09-08 16:17 1

摘要:Python深色版本withopen('data.txt', 'r') as f: data = f.read process(data)# 文件自动关闭,无需手动调用 close

分享兴趣,传播快乐,

增长见闻,留下美好!

亲爱的您,这里是LearningYard新学苑。

今天小编为大家带来文章

“刘心向学(42):上下文管理器(Context Managers)”

Share interest, spread happiness,

Increase knowledge, leave a beautiful!

Dear, this is LearningYard Academy.

Today, the editor brings you an article.

“Liu Xin Xiang Xue (42): Context Managers — Safe and Elegant Resource Management in Python”

Welcome to your visit.

一、思维导图(Mind Map)

你一定写过这样的代码:

You've probably written code like this:

Python深色版本f = open('data.txt', 'r')try: data = f.read process(data)finally: f.close

这段代码虽然安全,但不够优雅。而使用 with 语句,可以简化为:

This is safe but not elegant. With the with statement, it becomes:

Python深色版本withopen('data.txt', 'r') as f: data = f.read process(data)# 文件自动关闭,无需手动调用 close

这背后的核心机制就是上下文管理器

The magic behind this is context managers.

它确保无论代码正常执行还是发生异常,资源都能被正确释放。掌握它,你就能写出更安全、更 Pythonic 的代码。

They ensure that resources are properly released whether the code runs normally or an exception occurs. Mastering them allows you to write safer, more Pythonic code.

A context manager is an object that implements two methods:

__enter__(self):进入 with 语句时调用,通常返回要管理的资源。

__enter__(self): Called when entering the with block, typically returns the managed resource.

__exit__(self, exc_type, exc_value, traceback):退出 with 语句时调用,无论是否发生异常。

__exit__(self, exc_type, exc_value, traceback): Called when exiting the with block, regardless of whether an exception occurred.

只要一个对象实现了这两个方法,就可以用 with 语句管理。

Any object implementing these two methods can be used with the with statement.

Python深色版本withopen('log.txt', 'w') as f: f.write('Hello, World!')# 文件自动关闭Python深色版本import threadinglock = threading.Lockwith lock:# 安全执行临界区代码 shared_resource.update# 锁自动释放

抑制特定异常,无需写 try...except:

Log attribute read/write operations:

Python深色版本from contextlib import suppresswith suppress(FileNotFoundError): os.remove('temp.txt') # 如果文件不存在,也不会报错

__exit__ 的返回值控制异常传播

返回 True:抑制异常,with 块外不再抛出。

The return value of __exit__ controls exception propagation Return True : Suppresses the exception — no exception is raised outside the with block.

返回 False 或 None:正常传播异常。避免在 __enter__ 中抛出异常

Return False or None : Allows the exception to propagate normally.Avoid raising exceptions in __enter__

如果 __enter__ 失败,__exit__ 通常不会被调用,可能导致资源未初始化。

If __enter__ fails, __exit__ is typically not called, which may result in incomplete resource initialization or cleanup.

Context managers are a prime example of elegance and safety coexisting in Python. Through the with statement, they encapsulate resource acquisition and release within a clean, well-defined block, greatly improving code readability and robustness.

无论是文件、数据库、网络连接,还是自定义的临时状态管理,上下文管理器都能帮你:

Whether managing files, database connections, network sockets, or custom temporary states, context managers help you:

避免资源泄漏

Prevent resource leaks

简化异常处理

Simplify exception handling

提升代码可维护性

Improve code maintainability

The with statement is a perfect embodiment of these principles. Master it, and your Python code becomes not just safer — but truly elegant and expressive.

今天的分享就到这里了。

如果您对文章有独特的想法,

欢迎给我们留言,

让我们相约明天。

祝您今天过得开心快乐!

That's all for today's sharing.

If you have a unique idea about the article,

please leave us a message,

and let us meet tomorrow.

I wish you a nice day!

参考资料:通义千问

参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.

Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.

本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!

LearningYard新学苑

文字:song

排版:song

审核|hzy

来源:LearningYard学苑

相关推荐