[Tutor] Appending an extra column in a data file

Albert-Jan Roskam fomcl at yahoo.com
Thu Apr 11 13:24:31 CEST 2013


> Subject: Re: [Tutor] Appending an extra column in a data file
> 
> On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>>>     fin = open('old.dat')
>>>     fout = open('new.dat', 'w')
>>> 
>>>     with fin, fout:
>>>         for line in fin:
>> 
>> This has the same problems as contextlib.nested: An error raised while
>> opening 'new.dat' could prevent 'old.dat' from being closed 
> properly.
> 
> Thanks for pointing out the potential bug there. It's not a big
> problem in this case with the file open for reading. But, yeah, I'm
> hanging my head in shame here... ;)

Cool. This solves a problem it had with contextlib.nested some time ago.
(sorry for kinda hijacking this thread, but..)
Would it be safe (both __exit__ calls are guaranteed to be made) to use
code like this (if it worked, that is!)?

import sys
import contextlib

def someCloseFunc():
  print "Yaaay properly closed!"

@contextlib.contextmanager
def funcOne(arg):
  e = None
  try:
    yield arg
  except:
    e = sys.exc_info()[1]
    print e
  finally:
    someCloseFunc()
    if e:
      yield e
    yield None

funcTwo = funcOne
with contextlib.nested(funcOne("one-ish"), funcTwo("two-ish")) as (one, two):
  print one, two

* traceback
one-ish two-ish
Yaaay properly closed!
generator didn't stop
Yaaay properly closed!

Traceback (most recent call last):
  File "F:/mgr.py", line 23, in <module>
    print one, two
  File "C:\Program Files\Python27\lib\contextlib.py", line 24, in __exit__
    self.gen.next()
  File "C:\Program Files\Python27\lib\contextlib.py", line 121, in nested
    if exit(*exc):
  File "C:\Program Files\Python27\lib\contextlib.py", line 36, in __exit__
    raise RuntimeError("generator didn't stop after throw()")
RuntimeError: generator didn't stop after throw()
>>> 


More information about the Tutor mailing list