python `with` 语句用法的其他内置或实际示例? [英] Other builtin or practical examples of python `with` statement usage?

查看:63
本文介绍了python `with` 语句用法的其他内置或实际示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

__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; 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 模块为您提供 上下文管理器临时捕获警告.

许多库提供关闭行为,就像默认文件对象一样.其中包括 tarfilezipfile 模块.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆