Singleton generators as code blocks

Dave Benjamin ramen at
Sat Nov 22 01:12:10 CET 2003

Hey all,

I was just reflecting upon the old code block debate, and the thought
occurred to me that Python really does have a form of code blocks in its
implementation of generators. It was a pretty natural conclusion, and I'm
not sure why I didn't think of it before. For instance, compare Python's
generator-style iteration versus Ruby's codeblock-style iteration:

    for item in seq:
        print item
    seq.each { |item|
        puts item

Now, aside from the difference in mechanics, these two methods basically
accomplish the same thing. "seq" could be a regular list, or it could be a
lazy sequence. The syntax remains the same.

One of the simplest arguments in favor of codeblocks (or macros, but I'm not
going to go there <grin>) was the ability to write a function like
"with_open_file" that would open a file, perform some action on the file,
and then close the file automatically. I'm going to use this as an example
because of its simplicity, not because I think that there is an overwhelming
need for such a function.

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...'

for f in open_file('input.txt'):

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?

.:[ dave benjamin (ramenboy) -:- -:- ]:.
: d r i n k i n g   l i f e   o u t   o f   t h e   c o n t a i n e r :

More information about the Python-list mailing list