[Python-ideas] PEP 505: None-aware operators

Chris Angelico rosuav at gmail.com
Thu Jul 19 04:36:33 EDT 2018


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


More information about the Python-ideas mailing list