[Python-Dev] code blocks using 'for' loops and generators

Josiah Carlson jcarlson at uci.edu
Sat Mar 12 07:15:07 CET 2005


Brian Sabbey <sabbey at u.washington.edu> wrote:
> I would like to get some feedback on a proposal to introduce 
> smalltalk/ruby-like "code blocks" to python.  Code blocks are, among other 
> things, a clean way to solve the "acquire/release" problem [1][2].  This 
> proposal also touches on some of the problems PEP 288 [3] deals with.

[...]

My first reaction to the proposal was "ick".  Why?  Because every time
I've seen a mechanism for modifying the internals of generators
constructed using yield, the syntax has been awful; in my opinion
(whether my opinion means anything is another matter), the syntax you
propose is quite awful, and the functionality you desire does not
require syntax modification to be possible.

Strawman 1: the syntax

def pickled_file(name):
     f = open(name, 'r')
     l yield pickle.load(f)
     ^
------
|    f.close()
|    f = open(name, 'w')
|    pickle.dump(l, f)
|    f.close()
|
While this is currently a syntax error, it is not clear that an
assignment is happening /at all/, and I don't believe it would be /even
if/ if were documented, and every time someone opened up Python it said
"This is an assignment!" with an example. It looks too magical to me
(and from a guy who had previously proposed 'Some' as the opposite of
'None', that's saying something).


Strawman 2: putting data back into a generator

def pickled_file(name):
     f = open(name, 'r')
     yield pickle.load(f)
     f.close()
     f = open(name, 'w')
     pickle.dump(l, f)
     f.close()

Keep your code, except toss that leading 'l'.

for l in pickled_file('greetings.pickle'):
     l.append('hello')
     l.append('howdy')

Toss that 'continue l', and your code will work (as long as both the
function and the for are sitting in the same namespace).

Hrm, not good enough?  Use a Queue, or use another variable in a
namespace accessable to both your function and your loop.

Strawman 3: there is no strawman 3, but all lists need to have at least
3 items


I'm sorry if this email comes off harsh,
 - Josiah



More information about the Python-Dev mailing list