On Dec 31, 2019, at 14:58, Soni L. <fakedme...@gmail.com> wrote:
> 
> 
>> On 2019-12-31 7:28 p.m., Andrew Barnert via Python-ideas wrote:
>> 
>> The second is an “if try” statement, which tries an expression and runs the 
>> body if that doesn’t raise (instead of if it’s truthy), but jumps to the 
>> next elif/else/statement (swallowing the exception) if it does. The actual 
>> value of the expression is discarded, but the walrus operator takes care of 
>> that:
>> 
>>     if try 0, y, z := vec:
>>         # do yz plane stuff
>>     elif try x, 0, z := vec:
>>         # do xz plane stuff
>>     elif try x, y, 0 := vec:
>>         # do xy plane stuff
>>     elif x, y, z := vec:
>>         # do slow/imprecise/whatever 3D stuff
>>     else:
>>         raise TypeError(f'{vec} is not a 3-vector!')
>> 
>> Alternatively, this could just be a try expression that can be used 
>> anywhere: it’s truthy if evaluating doesn’t raise, falsey if it does. But I 
>> don’t think it’s needed anywhere but if/elif.

> while try?

Yeah, maybe. 

One of the inspirations here was Swift’s if let, and Swift does have a 
corresponding while let—which isn’t useful nearly as often, but is definitely 
useful sometimes. The first example I found online is this:

    var view: UIView? = self
    while let superview = view.superview {
        count += 1
        view = superview
    }

… which seems like it would make sense in Python:

    view = self
    while try view := view.superview:
        count += 1

… even if it actually works for a different reason (we’re not ending when we 
fail to bind the value out of an Optional that’s nil, but when we try to access 
an attribute on a value that’s None).

I suppose if it is worth doing, we do need to actually think about just if try, 
or if try and while try, or a general purpose try expression, rather than just 
crossing our fingers and saying YAGNI.


_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/JM5Z3KG72TBHQP4XQ76L6MMX2MDA3NG4/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to