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

Steven D'Aprano steve at pearwood.info
Thu Mar 1 01:00:03 CET 2012


Craig Yoshioka wrote:
> I've tried classes, decorators, and passing the conditional using 'as', as 
> suggested by Michael,  so I disagree that with is not suitable here since I have 
> yet to find a better alternative.  If you want I can give pretty concrete 
> examples in the ways they aren't as good.  Furthermore, I think it could be 
> argued that it makes more sense to be able to safely skip the with body without 
> the user of the with statement having to manually catch the exception 
> themselves.... we don't make people catch the StopIteration exception manually 
> when using iterators...

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.


> 1)  I can't think of many instances in python where a block of code can not be 
> conditionally executed safely:
>      if - obvious
>      functions - need to be called
>      loops - can have 0 or more iterations
>      try/except/finally - even here there is the same notion of the code blocks 
> being conditionally executed, just a bit more scrambled

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.



-- 
Steven



More information about the Python-ideas mailing list