[Python-ideas] revisit pep 377: good use case?

Craig Yoshioka craigyk at me.com
Thu Mar 1 01:46:58 CET 2012

On Feb 29, 2012, at 4:00 PM, Steven D'Aprano wrote:

> Sometimes we do. When you call next(it) manually, you are responsible for catching the exception manually. It is only flow-control tools (e.g. for loops, list comprehensions) that catch the exception for you.

I know that.  I'm arguing that 'with' could catch the for loop equivalent of StopIteration.  Or at least that's one implementation.

> Classes are blocks of code. If you want to conditionally skip executing all, or part, of a class block you wrap it in an if block. (Or try...except.) This is as it should be: the class statement is not a flow control statement.
> Nor is the def statement. In this case, the right concept is not in *calling* the function body, but in *compiling* the function body. Again, if you want to  conditionally skip compiling all or part of the function body, you have to wrap it in a flow control structure, if or try.
> We don't have any concept of:
>    class K: body
>    def f(): body
> where something inside the bodies invisibly determines whether or not the K block executes or the f block compiles.

? I'm just making an observation that there aren't many other places where an 'independent' block is 'guaranteed' to run.  I'm not arguing that something inside a block is magically preventing execution of the block.  The with keyword is 'outside' the block.  From within a block you can always return/break early anyways.

Think about it:

def test():
 # block is only executed if function is called

if True:
 # block is only executed if True

for x in items:
 # block is executed only for each item

class T(object):
  def m(self):
   # if method called

but I find it surprising that all of a sudden it's correct to assume: 

with x:
 # it's obvious this block will always run

that was not my assumption when I first became aware of 'with'.  For me it only meant that the indented block ran within some sort of context that was being managed for me.  Not saying the current use is wrong (though I do find it inconvenient and inconsistent), just that, other than 'with' I'm trying to think of a situation in which I'd put code in a new block where that code is guaranteed to run. I suppose I assumed that contexts were fancier if statements that were guaranteed to create and clean up various aspects of state.

> -- 
> Steven
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

More information about the Python-ideas mailing list