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

Eric Snow ericsnowcurrently at gmail.com
Tue Sep 29 19:15:36 CEST 2015


On Tue, Sep 29, 2015 at 8:56 AM, Paul Moore <p.f.moore at gmail.com> wrote:
> But it's not quite as obvious with multiple arguments where the target
> isn't the same as the parameter (for example with a constructor):
>
> def __init__(self, vertices=None, edges=None, weights=None, source_nodes=None):
>     if vertices is None:
>         self.vertices = []
>     else:
>         self.vertices = vertices
>     if edges is None:
>         self.edges = []
>     else:
>         self.edges = edges
>     if weights is None:
>         self.weights = {}
>     else:
>         self.weights = weights
>     if source_nodes is None:
>         self.source_nodes = []
>     else:
>         self.source_nodes = source_nodes

Personally I usually keep the defaults handling separate, like so:

def __init__(self, vertices=None, edges=None, weights=None, source_nodes=None):
    if vertices is None:
        vertices = []
    if edges is None:
        edges = []
    if weights is None:
        weights = {}
    if source_nodes is None:
        source_nodes = []

    self.vertices = vertices
    self.edges = edges
    self.weights = weights
    self.source_nodes = source_nodes

...and given the alternatives presented here, I'd likely continue
doing so.  To me the others are less distinct about how defaults are
set and invite more churn if you have to do anything extra down the
road when composing a default.  Regardless, YMMV.

[snip]
> In practice, of course, I never write a default() function at the
> moment, I just use multi-line ifs. Whether that means I'd use an or?
> operator, I don't know. Probably - but I'd likely consider it a bit of
> a "too many ways of doing the same thing" wart at the same time...

Right.  And it doesn't really pay for itself when measured against that cost.

-eric


More information about the Python-ideas mailing list