[Python-ideas] "else" expression ":"

Serhiy Storchaka storchaka at gmail.com
Thu Apr 18 22:04:29 CEST 2013


On 18.04.13 17:33, Chris Angelico wrote:
> On Fri, Apr 19, 2013 at 12:21 AM, Philipp A. <flying-sheep at web.de> wrote:
>> no, this is different; it’s not for booleans, but for assertions, and could
>> be used for e.g. exhaustive switches, e.g. it would make the first test in
>> the following unnecessary:
>>
>> if spam not in {"a", "b", "c"}:
>>      throw new ValueError("spam {} should be a, b, or c!".format(spam))
>> if spam == "a":
>>      foo()
>> elif spam == "b":
>>      bar()
>> else:
>>      baz()
>
> Or alternatively, you could write it as:
>
> if spam == "genuine watch":
>      foo()
> elif spam == "buy a college degree":
>      bar()
> elif spam == "rich guy wants to move money offshore":
>      baz()
> else:
>      raise ValueError("Unrecognized spam '%s'!" % spam)
>
> That removes the need to pre-check and match your if block.

Or alternative:

alternatives = {
     "genuine watch": foo,
     "buy a college degree": bar,
     "rich guy wants to move money offshore": baz,
}
try:
     alternative = alternatives[spam]
except KeyError:
     raise ValueError("Unrecognized spam '%s'!" % spam)
alternatives[spam]()





More information about the Python-ideas mailing list