Python多行with语句

发布于 2021-01-29 18:11:24

with在python中创建多行的干净方法是什么?我想在一个内打开多个文件with,但它足够靠右,足以在多行上显示。像这样:

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。所以我尝试了这个:

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

也是语法错误。但是,这可行:

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

但是,如果我想发表评论怎么办?这不起作用:

with Dummy() as a, Dummy() as b,\
     # my comment explaining why I wanted Dummy() as c\
     Dummy() as c:
    pass

\s的位置也没有任何明显的变化。

有没有一种干净的方法来创建with允许多行注释的多行语句?

关注者
0
被浏览
39
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这在Python 3.9中已修复!

    https://github.com/we-like-parsers/pegen/issues/229

    with (Dummy() as a,
            Dummy() as b,
            # my comment explaining why I wanted Dummy() as c
            Dummy() as c):
        pass
    

    这证明它有效:

    Python 3.9.0a6 (default, Jun 20 2020, 14:52:53) 
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.15.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [3]: with (open('x') 
       ...:        as f): 
       ...:     pass 
       ...:                                                                                                                                                                                                 
    ---------------------------------------------------------------------------
    FileNotFoundError                         Traceback (most recent call last)
    <ipython-input-3-47d5a51db08b> in <module>
    ----> 1 with (open('x')
          2        as f):
          3     pass
          4
    
    FileNotFoundError: [Errno 2] No such file or directory: 'x'
    
    In [4]:                                                                                                                                                                                                 
    Do you really want to exit ([y]/n)? y
    
    wPython 3.8.2 (default, May  8 2020, 20:08:31) 
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.15.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: with (open('x') 
       ...:       as f): 
       ...:     pass                                                                                                                                                                                        
      File "<ipython-input-1-e538abd13934>", line 2
        as f):
        ^
    SyntaxError: invalid syntax
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看