Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order of execution for multiple contextmanagers in python

I couldn’t find the answer for this question maybe someone could help me please?

Is the order of execution defined in case of using two contexts like that?

    with open('a.txt', 'w') as f1, open('b.txt', 'w') as f2:
       <some operation>

Am I guaranteed that the first context (here opening ‘a.txt’) will be executed before second (here opening ‘b.txt’)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

According to the language reference:

with A() as a, B() as b:
    SUITE

is semantically equivalent to:

with A() as a:
    with B() as b:
        SUITE

So yes, since A() will execute before the body is executed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading