with statement for two files

B

braver

Can open two files in a with statement:

with open(src) as readin, open(dst,"w") as writin: # WRONG: comma
doesn't work
...

-- so that you have transactional safety for two file descriptors?
The comma syntax doesn't work, but is there a way, except for

with open(src) as readin:
with open(dst,"w) as writin:
...

Cheers,
Alexy
 
D

Diez B. Roggisch

braver said:
Can open two files in a with statement:

with open(src) as readin, open(dst,"w") as writin: # WRONG: comma
doesn't work
...

-- so that you have transactional safety for two file descriptors?
The comma syntax doesn't work, but is there a way, except for

with open(src) as readin:
with open(dst,"w) as writin:
...

I'm not aware of any pre-defined context manager which does that.
But you can write your own context manager to do that, even a
generalized combinator for taking two managers and create one, like this:

with context_creator(open, [src], open, [dst, "w"]) as readin, writin:
...

A fundamental problem though would be that the semantics become
difficult. If closing the "outer" file fails, it's impossible to
"rollback" the inner one.

So I think it really is better to use the nested with, which makes it
crystal clear that the inner block might succeed independently from the
outer one.

Diez
 
P

Paul Rubin

braver said:
with open(src) as readin, open(dst,"w") as writin: # WRONG: comma
doesn't work
...
-- so that you have transactional safety for two file descriptors?

use contextlib.nexted().
 
D

Diez B. Roggisch

Paul said:
use contextlib.nexted().

You mean contextlib.nested I guess. Didn't know about that module, cool!

However, the fundamental problem stays: rolling back only works if the
innermost context fails.

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top