[Python-ideas] PEP 505 (None coalescing operators) thoughts

Andrew Barnert abarnert at yahoo.com
Tue Sep 29 22:33:08 CEST 2015

On Sep 29, 2015, at 09:58, Emile van Sebille <emile at fenx.com> wrote:
>> On 9/29/2015 9:20 AM, Rob Cliffe wrote:
>> Why not
>> def __init__(self, vertices=None, edges=None, weights=None,
>> source_nodes=None):
>>     self.vertices     = vertices     if vertices     is not None else []
>>     self.edges        = edges        if edges        is not None else []
>>     self.weights      = weights      if weights      is not None else {}
>>     self.source_nodes = source_nodes if source_nodes is not None else []
> I don't understand why not:
>      self.vertices     = vertices     or []
>      self.edges        = edges        or []
>      self.weights      = weights      or {}
>      self.source_nodes = source_nodes or []

Because empty containers are just as falsey as None.

So, if I pass in a shared list, your "vertices or []" will replace it with a new, unshared list; if I pass a tuple because I need an immutable graph, you'll replace it with a mutable list; if I pass in a blist.sortedlist, you'll replace it with a plain list. Worse, this will only happen if the argument I pass happens to be empty, which I may not have thought to test for.

This is the same reason you don't use "if spam:" when you meant "if spam is not None:", which is explained in PEP 8.

Also, I believe the PEP for ternary if-else explains why this is an "attractive nuisance" misuse of or, as one of the major arguments for why a ternary expression should be added.

More information about the Python-ideas mailing list