Feature suggestion -- return if true

jek jek7777777 at gmail.com
Mon Aug 21 08:44:53 EDT 2017


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.



More information about the Python-list mailing list