[Python-ideas] PEP 505: None-aware operators
Brice Parent
contact at brice.xyz
Thu Jul 19 04:48:48 EDT 2018
Le 19/07/2018 à 10:36, Chris Angelico a écrit :
> On Thu, Jul 19, 2018 at 5:45 PM, Brice Parent <contact at brice.xyz> wrote:
>> The biggest drawback of this, is that (if I understand it well), it may be
>> done quite easily without any change to the language:
>>
>> def first_set(*elements): # please don't mind the name of the function,
>> it's not the purpose here
>> """ Will return the first element that is not None """
>> for element in elements:
>> if element is not None:
>> return element
>>
>> raise AllNoneException()
>>
>> first_set(3, 5) # -> 3
>> first_set(None, 5) # -> 5
>> first_set(None, None, 8, 10) # -> 8
>> first_set(None, Car(model="sport")).buy() # calling
>> Car(model="sport").buy()
>> first_set(None, ["a", "b", "c"])[1] # -> "b"
>> first_set(None, None) # -> exception is raised
>>
>> (note that such function could even accept a "rejected_values" kwarg, like
>> `rejected_values=(None, [], "")`, just by replacing the `if` clause by `if
>> element not in rejected_values:`)
> No it can't, for the same reason that the 'and' and 'or' operators
> can't be implemented cleanly as functions: it short-circuits. The
> right-hand operator _will not_ be evaluated unless the left is None.
>
> ChrisA
Thanks for the clarification, I didn't think about that.
It doesn't make it beautiful or easily readable, but at least, I
understand how it may be useful then!
More information about the Python-ideas
mailing list