python gripes survey

Hannu Kankaanpää hanzspam at yahoo.com.au
Tue Aug 26 04:44:37 EDT 2003


"Ryan Lowe" <ryanlowe0 at msn.com> wrote in message news:<0dw2b.194888$_R5.73038469 at news4.srv.hcvlny.cv.net>...
> are there more
> complicated uses of code blocks that would make them more powerful than
> python's generators?

When you want to do something else than iteration. Such as the
common example (adapting Ruby's |variable|-syntax)

with_file('file.dat', 'rb') |f|:
    data = f.read()

Which currently has to be written as

f = file('file.dat', 'rb')
try:
    data = f.read()
finally:
    f.close()

And that's pretty verbose. If an exception is thrown inside
iteration, there's no way for the generator to catch it.
So Python can't do it like this:

for f in with_file('file.dat', 'rb'):
    data = f.read()


def with_file(*args):
    f = file(*args)
    try:
        yield f
    finally:
        f.close()

It would look pretty strange too.

One could do this with lambdas or nested functions in Python,
since they are "code blocks". But their definition and access
to local variables is awkward (for this situation):

data = [None]
def reader(f):
    data[0] = f.read()
with_file('file.dat', 'rb', reader)

Way too ugly to be used.




More information about the Python-list mailing list