This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author gvanrossum
Recipients
Date 2004-05-13.03:58:13
SpamBayes Score
Marked as misclassified
Message-id
In-reply-to
Content
Logged In: YES 
user_id=6380

On why the first expr should be evaluated immediately:

Consider sum(x for x in foo()). Now suppose there's a bug in
foo() that raises an exception, and a bug in sum() that
raises an exception before it starts iterating over its
argument. Which exception would you expect to see? I'd be
surprised if the one in sum() was raised rather the one in
foo(), since the call to foo()  is part of the argument to
sum(), and I expect arguments to be processed before the
function is called.

OTOH, in sum(bar(x) for x in foo()), where sum() and foo()
are bugfree, but bar() raises an exception, we have no
choice but to delay the call to bar() until sum() starts
iterating -- that's part of the contract of generators.
(They do nothing until their next() method is first called.)

Ditto for subsequent iterables if nested for loops are used:
in sum(x*y for x in range(10) for y in bar(x)), there are 10
calls to bar(), with arguments supplied by the first (outer)
for loop, and we have no choice but to delay even the first
call to bar() until sum() calls next() on its argument.

I know this isn't the easiest thing to implement, but I
still think it's the right thing. The generator function for
the last example would be something like

def G(arg):
    for x in arg:
        for y in bar(x):
            yield x*y

and the call to sum() would be

sum(G(range(10)))
History
Date User Action Args
2007-08-23 15:31:40adminlinkissue872326 messages
2007-08-23 15:31:40admincreate