Singleton generators as code blocks

Jp Calderone exarkun at intarweb.us
Fri Nov 21 20:45:11 EST 2003


On Sat, Nov 22, 2003 at 12:12:10AM -0000, Dave Benjamin wrote:
> Hey all,
> 
> [snip]
> 
> In Python, I was able to implement a generator version quite simply. It
> seemed so obvious that I thought maybe there was a thread in the past where
> this was already mentioned; if so, forgive me for stating the obvious:
> 
> def open_file(filename, mode='r'):
>     f = file(filename, mode)
>     yield f
>     print 'closing...'
>     f.close()
> 
> for f in open_file('input.txt'):
>     print f.read()
> 
> The above code prints the conntents of the file "input.txt", then the string
> "closing...", and then closes the file.
> 
> This seems to illustrate that generators and codeblock-accepting functions
> are really very similar, and that maybe codeblocks wouldn't really add much
> of anything to Python after all. I still have to wonder if maybe I'm missing
> something here...
> 
> Has anyone used this sort of "singleton generator" technique?

  This is a pretty nifty approach, but it seems to have (at least?) one serious
drawback.  If the body of the loop raises an exception, the generator is
never resume, and the cleanup (or whatever) is never run.

  A way to reformulate the above without losing its conciseness eludes me
currently.

  Jp





More information about the Python-list mailing list