python with语句,Python多行with语句

What is a clean way to create a multi-line with in python? I want to open up several files inside a single with, but it's far enough to the right that I want it on multiple lines. Like this:

class Dummy:

def __enter__(self): pass

def __exit__(self, type, value, traceback): pass

with Dummy() as a, Dummy() as b,

Dummy() as c:

pass

Unfortunately, that is a SyntaxError. So I tried this:

with (Dummy() as a, Dummy() as b,

Dummy() as c):

pass

Also a syntax error. However, this worked:

with Dummy() as a, Dummy() as b,\

Dummy() as c:

pass

But what if I wanted to place a comment? This does not work:

with Dummy() as a, Dummy() as b,\

# my comment explaining why I wanted Dummy() as c\

Dummy() as c:

pass

Nor does any obvious variation on the placement of the \s.

Is there a clean way to create a multi-line with statement that allows comments inside it?

解决方案

Given that you've tagged this Python 3, if you need to intersperse comments with your context managers, I would use a contextlib.ExitStack:

from contextlib import ExitStack

with ExitStack() as stack:

a = stack.enter_context(Dummy()) # Relevant comment

b = stack.enter_context(Dummy()) # Comment about b

c = stack.enter_context(Dummy()) # Further information

This is equivalent to

with Dummy() as a, Dummy() as b, Dummy() as c:

This has the benefit that you can generate your context managers in a loop instead of needing to separately list each one. The documentation gives the example that if you want to open a bunch of files, and you have the filenames in a list, you can do

with ExitStack() as stack:

files = [stack.enter_context(open(fname)) for fname in filenames]

If your context managers take so much screen space that you want to put comments between them, you probably have enough to want to use some sort of loop.

As Mr. Deathless mentions in the comments, there's a contextlib backport on PyPI under the name contextlib2. If you're on Python 2, you can use the backport's implementation of ExitStack.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值