[Python-ideas] "while ... try" - block or "for ... try" - block
Manuel Bärenz
manuel at enigmage.de
Thu Jan 12 11:51:24 CET 2012
On 11.01.2012 17:58, Jim Jewett wrote:
> 2012/1/11 Manuel Bärenz <manuel at enigmage.de>:
>
>> while expr try:
>> suite1
>> except SomeException:
>> suite2
>> else:
>> suite3
> Without your explanation, I would still have assumed that the
> exception terminated the while.
> #Steve's comment:
> people will get confused by the construct
> and repeatedly be surprised it doesn't do what they expect.
Ok, you convinced me that this is not intuitive for most people.
Normally, one expects the try block to work and not to fail. So
continuing the loop on failure and not on success is counterintuitive.
> retry=WaitPolicy('sleep_and_retry', 3)
>
> with ensure_network(onfail=retry) as network:
> with connect_to_server(transport=network, onfail=retry):
> download_stuff()
That's a nice and Pythonic suggestion. Thanks.
On 12.01.2012 01:00, Steven D'Aprano wrote:
> This conflates two naturally distinct operations, looping and exception
> handling, into a single construct that tries to do both. "Loop" is a natural
> operation. "Catch exceptions" is a natural operation. "Loop and catch
> exceptions" is not, it is two operations and so should be written as two
> operations.
In these words, I wanted to point out that "Loop until it works" is a
natural operation and should have a Python control flow.
> The syntax also clashes with existing while...else.
Not syntactically:
>>> while True try:
File "<stdin>", line 1
while True try:
^
SyntaxError: invalid syntax
The interpreter could easily distinguish the two, since try is a
reserved keyword..
> The try clause can be easily missed
> while skimming code,
Very good point.
> Your proposal looks like you've picked two block constructs, a while
> loop and a try block, and nailed them together.
Sorry, I'll have to defend against that a bit. This idea really came
from a (simple) usecase. I did a performance test of the
functools.lru_cache decorator against a naive self-written memoize class
and found me writing:
try:
result = self.cache[n]
except KeyError:
result = self.cache[n] = self.f(n)
return result
I would have wanted to write something like:
while True try:
return self.cache[n]
except KeyError:
self.cache[n] = self.f(n)
That's how I came up with the idea.
But you presented enough reasonable arguments against it such that I
won't consider it anymore.
Thanks for your comments.
More information about the Python-ideas
mailing list