Feature suggestion -- return if true

Ian Kelly ian.g.kelly at gmail.com
Mon Aug 21 11:06:20 EDT 2017


On Mon, Aug 21, 2017 at 8:39 AM, alister via Python-list
<python-list at python.org> wrote:
> On Mon, 21 Aug 2017 05:44:53 -0700, jek wrote:
>> This is a very old post, but since I just though I would like a
>> conditional return like this, and checked for previous proposals, I
>> thought I'd give my opinion.
>>
>> Unfortunately only about 8 of the 67 replies actually answer the
>> question, and there isn't any overwhelming consensus to if a conditional
>> return would be good or not. Most (if not all) people dislike the syntax
>> though, and I agree.
>>
>> So, my proposal would be the syntax:
>>
>> return if <expr>
>>
>> That is more pythonic than return?, does not involve a new keyword, and
>> is "human readable" in a way similar to e.g the ternary statement.
>>
>> //jek
>>
>> tue 12 apr 2011 zildjohn01 wrote:
>>> I propose the following syntax:
>>>
>>>     return? expr
>>>
>>> be expanded to
>>>
>>>     _temp = expr if _temp: return _temp
>>
>> As a side note, for the syntax of a cache, that was discussed a bit, I
>> sometimes to use:
>>
>> try:
>>   return cache[key]
>> except KeyError:
>>   ret = cache[key] = compute(key)
>>   return ret
>>
>> In my limited test it is a bit quicker than both "if x in cache" and
>> "v=cache.get(x)" (~ 0.9, 1.1 and 1.3 seconds) Though it might depend on
>> the hash complexity and the number of cache hits vs misses, so I guess
>> either syntax would do fine.
>
> how does this syntax enable you to specify the value to be returned?
> What new benefits would this addition provide beyond what is already
> available?

The value to be returned is the same as the value of the condition. In
my view that is the only benefit of this syntax: it provides a natural
way to specify that without evaluating the return value twice. If you
want to return a different value, there's already a great way to do
that:

if <expr>:
    return <other_expr>



More information about the Python-list mailing list