[Python-ideas] PEP 505 (None coalescing operators) thoughts
Steven D'Aprano
steve at pearwood.info
Wed Sep 30 03:32:36 CEST 2015
On Tue, Sep 29, 2015 at 12:07:10PM -0600, Carl Meyer wrote:
> On 09/29/2015 12:04 PM, Brian O'Neill wrote:
> > A further virtue of
> >
> > self.vertices = vertices or []
> >
> > and the like is that they coerce falsy parameters of the wrong type to the falsy object of the correct type.
> >
> > E.g. if vertices is '' or 0, self.vertices will be set to [], whereas the ternary expression only tests
> >
> > for not-None so self.vertices will be set to a probably crazy value.
>
> Doesn't seem like a virtue to me, seems like it's probably hiding a bug
> in the calling code, which may have other ramifications. Better to have
> the "crazy value" visible and fail faster, so you can go fix that bug.
Agreed.
Assuming the function is intended to, and documented as, using the
passed in "vertices", using `or` is simply wrong, in two ways:
- if vertices is a falsey value of the wrong type, say, 0.0, it will be
silently replaced by [] instead of triggering an exception (usually a
TypeError or AttributeError);
- if vertices is a falsey value of the right type, say
collections.deque(), it will be silently replaced by [].
In the first case, the code is hiding a bug in the caller. In the second
case, its a bug in the called code.
I am very sad to see how many people still use the error-prone `x or y`
idiom inappropriately, a full decade after PEP 308 was approved.
(Depending on where you are in the world, it was ten years ago today, or
yesterday.) `x or y` still has its uses, but testing for None is not one
of them.
--
Steve
More information about the Python-ideas
mailing list