[Python-Dev] PEP 463: Exception-catching expressions

Eric Snow ericsnowcurrently at gmail.com
Sat Feb 22 03:28:01 CET 2014


On Fri, Feb 21, 2014 at 6:48 PM, Yury Selivanov <yselivanov.ml at gmail.com> wrote:
> This new syntax won't magically fix all the code either.
> But it may let people write code like this:
>
>   # I'm sorry, I really can't read this.
>
>   logging.info("Message shown to user: %s",((cache[k]
>       except LookupError:
>           (backend.read(k) except OSError: 'Resource not available')
>       )
>       if check_permission(k) else 'Access denied'
>   ) except BaseException: "This is like a bare except clause")

You could argue the same thing about people chaining ternary
conditional expressions (because it would be about as hard to read).
Ditto for lambda.  These expression forms (and expressions in general)
are useful for brief snippets of code.  If someone wants to write
expressions that span multiple lines like that, then that's their
problem.  I don't see how the PEP 463 syntax will make it more likely
that someone will abuse expression syntax like that.

>
> or this:
>
>   # We happily mask exceptions from getgrnam
>
>   g = grp.getgrnam(tarinfo.gname)[2] except KeyError: tarinfo.gid

Either you'd get this anyway:

  try:
      g = grp.getgrnam(tarinfo.gname)[2]
  except KeyError:
      g = tarinfo.gid

or your fallback value will be evaluated prematurely:

  g = grp.getgrnam(tarinfo.gname).get(2, tarinfo.gid)

So to get this right:

  _info = grp.getgrnam(tarinfo.gname)
  try:
      g = _info[2]
  except KeyError:
      g = tarinfo.gid

vs.

  _info = grp.getgrnam(tarinfo.gname)
  g = _info[2] except KeyError: tarinfo.gid

> I can't believe you find
>
>    list[42] except IndexError: 'spam'
>
> to be better than
>
>    list.get(42, 'spam')

What about:

  list[42] except IndexError: something_expensive()

or:

  list[42] except IndexError: something_lazy_really_we_want_to_put_off()

-eric


More information about the Python-Dev mailing list