[Tutor] Appending an extra column in a data file
Oscar Benjamin
oscar.j.benjamin at gmail.com
Thu Apr 11 13:56:05 CEST 2013
On 11 April 2013 12:24, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
>
>> 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!)?
Partly because it doesn't work I really can't figure out what you're
trying to do.
>
> 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:
I guess you already know that the lines two lines below will break the
contextmanager decorator:
> yield e
> yield None
>
What effect are you actually wanting from the two lines below (I'm
assuming that you didn't want the error message shown)? Is it
significant that funcTwo is funcOne, or is that just to keep the
demonstration simple?
> 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()
>>>>
Oscar
More information about the Tutor
mailing list