Python 3.10 – Parenthesized Context Managers

Python 3.10 is coming out next month, so now is the time to start talking about the new features that it will contain. The core developers of Python recently announced that they are adding parenthesized context managers, which is a bugfix to a bug where Python 3.9 and earlier did not support parentheses for continuation across lines.

You could still have multiple context managers, but they couldn’t be in parentheses. Basically, it makes the code look a bit awkward. Here is an example using Python 3.8:

>>> with (open("test_file1.txt", "w") as test, 
          open("test_file2.txt", "w") as test2): 
        pass                                                                 

File "<input>", line 1
    with (open("test_file1.txt", "w") as test,
                                      ^
SyntaxError: invalid syntax

Interestingly enough, this same code appears to work correctly in Python 3.9 even though it isn’t officially supported. If you go read the original bug report there is a mention there that the addition of the PEG Parser (PEP 617) should fix the issue.

This is somewhat reminiscent of the time when Python dictionaries were unordered until an implementation detail made them ordered in Python 3.6, but not officially ordered until Python 3.8.

Regardless, the change has been approved in Python 3.10, which makes all of the following example valid code:

with (CtxManager() as example):
    ...

with (
    CtxManager1(),
    CtxManager2()
):
    ...

with (CtxManager1() as example,
      CtxManager2()):
    ...

with (CtxManager1(),
      CtxManager2() as example):
    ...

with (
    CtxManager1() as example1,
    CtxManager2() as example2
):
    ...

You can read more about this new “feature” in the What’s New section for Python 3.10.