with statement for two files

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • braver

    with statement for two files

    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
  • Diez B. Roggisch

    #2
    Re: with statement for two files

    braver schrieb:
    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

    Comment

    • Paul Rubin

      #3
      Re: with statement for two files

      braver <deliverable@gm ail.comwrites:
      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.next ed().

      Comment

      • Diez B. Roggisch

        #4
        Re: with statement for two files

        Paul Rubin wrote:
        braver <deliverable@gm ail.comwrites:
        >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.next ed().
        You mean contextlib.nest ed I guess. Didn't know about that module, cool!

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

        Diez

        Comment

        • greg

          #5
          Re: with statement for two files

          Diez B. Roggisch wrote:
          Paul Rubin wrote:
          >
          use contextlib.next ed().
          >
          You mean contextlib.nest ed I guess.
          Although "nexted" is an intriguing-sounding word. I wonder
          what it could mean?

          --
          Greg

          Comment

          Working...