python – 如何__enter__ n上下文管理器?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 如何__enter__ n上下文管理器?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1570字,纯文字阅读大概需要3分钟。
内容图文
![python – 如何__enter__ n上下文管理器?](/upload/InfoBanner/zyjiaocheng/818/c482075cbd0e48478e74f35bfd8adbb2.jpg)
使用with语句,我们可以只使用一个级别的缩进/嵌套来输入许多上下文处理程序:
>>> from contextlib import contextmanager
>>> @contextmanager
... def frobnicate(n):
... print('frobbing {}'.format(n))
... yield
...
>>> frob1 = frobnicate(1)
>>> frob2 = frobnicate(2)
>>> with frob1, frob2:
... pass
...
frobbing 1
frobbing 2
但这似乎不起作用:
>>> frobs = [frobnicate(1), frobnicate(2)]
>>> with *frobs:
... pass
# SyntaxError: invalid syntax
我们如何输入n个上下文管理器而不必手动写出每个上下文管理器?
解决方法:
python2.7让contextlib.nested做到了这一点,但由于容易出错的怪癖而被弃用.
This function has two major quirks that have led to it being deprecated. Firstly, as the context managers are all constructed before the function is invoked, the
__new__()
and__init__()
methods of the inner context managers are not actually covered by the scope of the outer context managers. That means, for example, that usingnested()
to open two files is a programming error as the first file will not be closed promptly if an exception is thrown when opening the second file.Secondly, if the
__enter__()
method of one of the inner context managers raises an exception that is caught and suppressed by the__exit__()
method of one of the outer context managers, this construct will raise RuntimeError rather than skipping the body of the with statement.
python3.3使用contextlib.ExitStack做得更好,看起来像:
from contextlib import ExitStack
with ExitStack() as stack:
contexts = [stack.enter_context(frobnicate(i)) for i in range(2)]
...
有关backport到python2.x代码,请参阅contextlib2.
内容总结
以上是互联网集市为您收集整理的python – 如何__enter__ n上下文管理器?全部内容,希望文章能够帮你解决python – 如何__enter__ n上下文管理器?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。