python `with` 语句用法的其他内置或实际示例? [英] Other builtin or practical examples of python `with` statement usage?
问题描述
在 __enter__
和 __exit__
用例的 python 文件对象实现之外,有人有真实世界的例子吗?最好是你自己的,因为我想要实现的是一种更好的方式来概念化将使用它的情况.
Does anyone have a real world example outside of python's file object implementation of an __enter__
and __exit__
use case? Preferably your own, since what I'm trying to achieve is a better way to conceptualize the cases where it would be used.
我已经阅读了这个.
而且,这里是 Python 文档的链接. >
推荐答案
有许多用途.就在我们的标准库中:
There are many uses. Just in the standard library we have:
sqlite3
;使用 连接作为上下文管理器 表示提交或中止事务.
sqlite3
; using the connection as a context manager translates to committing or aborting the transaction.
unittest
;使用 assertRaises
作为上下文管理器允许您断言引发了异常,然后测试异常的各个方面.
unittest
; using assertRaises
as a context manager lets you assert an exception is raised, then test aspects of the exception.
十进制
;localcontext
管理十进制数精度,四舍五入和其他方面.
decimal
; localcontext
manages decimal number precision, rounding, and other aspects.
threading
对象,例如锁、信号量和条件是 上下文管理器也是;让您获得一组语句等的锁.
threading
objects such as locks, semaphores and conditions are context managers too; letting you obtain a lock for a set of statements, etc.
warnings
模块为您提供 上下文管理器临时捕获警告.
许多库提供关闭行为,就像默认文件对象一样.其中包括 tarfile
和 zipfile
模块.
many libraries offer closing behaviour, just like the default file object. These include the tarfile
and the zipfile
modules.
Python 自己的 test.test_support
模块 使用多个上下文管理器来检查特定警告、捕获 stdout
、忽略特定异常并临时设置环境变量.
Python's own test.test_support
module uses several context managers, to check for specific warnings, capture stdout
, ignore specific exceptions and temporarily set environment variables.
任何时候您想检测代码块何时开始和/或结束,您都想使用上下文管理器.在使用 try:
和 finally:
套件来保证清理之前,请改用上下文管理器.
Any time you want to detect when a block of code starts and / or ends, you want to use a context manager. Where before you'd use try:
with a finally:
suite to guarantee a cleanup, use a context manager instead.
这篇关于python `with` 语句用法的其他内置或实际示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!