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

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Thu Jul 19 23:30:39 EDT 2018


Terry Reedy writes:
 > On 7/19/2018 4:32 AM, Stephen J. Turnbull wrote:

 > > make me cringe.  Exactly one of two things is true:
 > 
 > It seems to me that the problem is returning None.

Exactly, but this seems to indicate that the problem I'm talking about
is the code.  It's not; my issue is with the use of THIS code as an
example justifying "??".

 > The premise of returning None as default is that users can follow
 > with conditional code.  If we now think that this is too much of a
 > burden, we should stop returning None, at least by default.

Note that in the case of an MUA, code might look like something like
this:

    class BaseSaveObject(object):        # NOTE NAME CHANGE!
        def find_content_type(self, filename):
            ctype, encoding = mimetypes.guess_type(filename)
            while ctype is None:
                ctype = input('Couldn't recognize MIME type. Ideas?")
                ctype = self.validate_mimetype(ctype)  # returns None on bad
            return ctype

So returning "application/octet-stream" is probably inappropriate if
parsing the message header for Content-Type fails.

I'm not sure why you say "burdensome".  Using "x() or y()" *because*
it short-circuits is idiomatic (although some deprecate it).  The main
point of "??" is that "or" is not good enough because it does the same
thing with other falsies that it does with None.  There are other
tweaks (such as very high precedence), but that's the main thing.

What I'm looking for is a set of examples where "or" won't do, and
explanations of *why* that is true and why programmers *won't* abuse
"??" to create less resilient code, to balance against the avalanche
of examples where "??" leads to less resilient code, such as this
case.

Note that if you want to use "??" rather than "or", there's at least
one other falsie that you want to *avoid* a default for, and then in
cases like this one, the question is "why aren't you checking for it
to prevent exceptions in a module written long long ago in a galaxy
far far away?"

 > > 1.  mimetypes.guess_type guarantees that the only falsie it will ever
 > >      return is None, or
 > > 
 > > 2.  it doesn't.
 > 
 > or
 > 3. it never returns anything other than a non-blank string unless the 
 > user so requests.

That would be nice, but that's off-topic.  The point here is that
Steve ripped a page from Tim's book and transformed a pile of real
code.  (This deserves a standing ovation IMO!)  So he has to take the
API as it is, warts and all.

Steve



More information about the Python-ideas mailing list