Python多行with语句 [英] Python multi-line with statement

查看:211
本文介绍了Python多行with语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中创建多行with的干净方法是什么?我想在一个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

很遗憾,这是SyntaxError.所以我尝试了这个:

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.

是否有一种干净的方法来创建多行的with语句,该语句允许在其中添加注释?

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

推荐答案

鉴于您已经标记了此Python 3,如果需要在上下文管理器中插入注释,则可以使用

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

这等效于

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.

正如Deathless先生在评论中提到的那样,PyPI下的PyPI上有一个 contextlib backport 名称contextlib2.如果您使用的是Python 2,则可以使用ExitStack的backport实现.

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.

这篇关于Python多行with语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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