4 ms·
In my second example, I expect i to not be in the scope. The variable i only makes sense inside the list comprehension and should not be randomly introduced int
by tikhonj 14y ago
In my second example, I expect i to not be in the scope. The variable i only makes sense inside the list comprehension and should not be randomly introduced into the outer scope.
For the first example, I don't see how you could replace it with yield, especially if the function foo has to normally return a value when it's used. The core idea is to count how many times foo is called without altering the call site at all. Also, this is an entirely trivial example to illustrate the scoping issue; in practice, there are more complicated reasons to want to set non-local variables, especially from things like helper functions.
- LeonidasXIV 14y agoThis scope-leaking was fixed in Python 3 afair (I don't have a Python 3 to verify just now).