[Python-ideas] except expression

Rob Cliffe rob.cliffe at btinternet.com
Wed Feb 19 02:22:17 CET 2014


On 19/02/2014 01:00, Chris Angelico wrote:
> On Wed, Feb 19, 2014 at 11:10 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>>          for key in sequence:
>>              x = (d1[key] except KeyError: (d2[key] except KeyError: 0))
>>
>> Take the colons and brackets out, and I think it is less readable:
>>
>>              x = d1[key] except KeyError d2[key] except KeyError 0
>>
>> and ambiguous.
>>
>> By the way, I think this is a good example for the PEP (Chris are you
>> reading?). You might be tempted to re-write this as:
>>
>>              x = d1.get(key, d2.get(key, 0))
>>
>> which is shorter, but the semantics are different. If the second case,
>> you have to pre-calculate the fallback, which may be expensive, while in
>> the exception form, you only calculate the fallback if the first lookup
>> actually fails.
Yo!  I actually mentioned this way of rewriting it, but I missed that 
the semantics were different and more expensive.
Long live this proposal!
(Although to carp, I think that the colons are desirable but the 
brackets are not.)
> I certainly am reading :) Going a bit further by having the final
> fall-back be a function call (highlighting the fact that it may be
> expensive).
>
> """
> Consider this example of a two-level cache::
>      for key in sequence:
>          x = (lvl1[key] except KeyError: (lvl2[key] except KeyError: f(key)))
>
> This cannot be rewritten as::
>          x = lvl1.get(key, lvl2.get(key, f(key)))
>
> which, despite being shorter, defeats the purpose of the cache, as it must
> calculate a default value to pass to get(). The .get() version calculates
> backwards; the exception-testing version calculates forwards, as would be
> expected.
> """
>
> ChrisA
Again, yo!  Surely we are on to a good thing here with this proposal?
Rob Cliffe
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
> -----
> No virus found in this message.
> Checked by AVG - www.avg.com
> Version: 2012.0.2247 / Virus Database: 3705/6604 - Release Date: 02/18/14
>
>



More information about the Python-ideas mailing list