On PEP 312: simple implicit lambda

Dan Schmidt dfan at dfan.org
Sun Feb 16 12:15:05 EST 2003


Andrew Bennetts <andrew-pythonlist at puzzling.org> writes:

| On Sun, Feb 16, 2003 at 04:47:11PM +0200, Christos TZOTZIOY Georgiou wrote:
|| 
|| Take for example:
|| 
|| data = file_object.read(4096)
|| while data:
||     # process here
||      data = file_object.read(4096)
|| 
|| (In this simple case, the need to avoid duplication is not that strong,
|| so it is a bad example, but it's just an idea that popped up in my mind
|| a few minutes ago;  I won't stand up to it if proven to be stupid :)
|| There are cases with if...elif...else constructs where duplicate code is
|| used too, so if needed, I will find more examples.)
|
| Why not simply:
|
|     data = 'dummy'
|     while data:
|         data = file_object.read(4096)
|         # process here
|
| This avoids the duplication quite neatly.

But it doesn't do the same thing, as it does the processing a final
time even when data becomes false.  The following code does do the
same as the original:

  while True:
     data = file_object.read(4096)
     if not data:
        break
     # process here

but it's a little awkward; it's kind of weird that we really do want
to have a while loop with data not being false as the condition, but
are forced to instead make the condition be True and break out in the
middle.

In Python, to code these 'loop and a half' constructs, you have to
either duplicate some code, as Christos did, or put a conditional
break halfway through the loop, as I did.

Dan

-- 
http://www.dfan.org




More information about the Python-list mailing list