For review: PEP 343: Anonymous Block Redux and Generator Enhancements

Nicolas Fleury nidoizo at yahoo.com
Sun Jun 5 07:32:44 CEST 2005


Andrew Dalke wrote:
> Consider the following
>
> server = open_server_connection()
> with abc(server)
> with server.lock()
> do_something(server)
>
> server.close()
>
> it would be translated to
>
> server = open_server_connection()
> with abc(server):
>   with server.lock()
>     do_something(server)
>     server.close()
>
> when I meant for the first code example to be implemented
> like this
>
> server = open_server_connection()
> with abc(server):
>   with server.lock()
>     do_something(server)
>
> server.close()

That's an interesting point.  But I'm not sure if it is a realistic
error.  It would be like using a with-statement without knowing what it
does.  Also, and it seems we agree, these cases are very rare.

>
> (It should probably use the with-block to handle the server open
> and close, but that's due to my lack of imagination in coming up
> with a decent example.)
>
> Because of the implicit indentation it isn't easy to see that
> the "server.close()" is in an inner block and not at the outer
> one that it appears to be in.  To understand the true scoping
> a reader would need to scan the code for 'with' lines, rather
> than just looking at the layout.

But with both syntaxes you only look at the indentation layout, no?  If
you want to know the "scope" of something as you said, it means you have
already scan its "with" statement.  You only need after that to look at
the indentation layout, as with indentation syntax.

It's however less obvious at first look that with-statements implies
some scope, but I feel that Python newcomers usually do the opposite
error instead, thinking their variables have a defined scope as in some
other languages.

> A test for how often this is needed would be to look in existing
> code for the number of try/finally blocks.  I have seen and
> written some gnarly deeply stacked blocks but not often - once
> a year?
>
> That's not to say it's a good indicator.  A lot of existing code
> looks like this

I agree.  It's hard to find a good indicator.  In my case I use both my
Python code (with try/finally typically ending a function) and my C++
code (with typically no {} block created for RAII object scope).  So, my
conclusion, most of the time the indentation will be useless.

> What I mean by all of this is that the new PEP may encourage
> more people to use indented blocks, in a way that can't be
> inferred by simply looking at existing code.  In that case
> your proposal, or the one written

Totally agree.  The with-statement will open the door to new programming
patterns in Python and it's hard to tell from status quo how much it
will be used.

Regards,
Nicolas





More information about the Python-list mailing list