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

Nick Coghlan ncoghlan at gmail.com
Sat Feb 22 16:29:15 CET 2014

On 22 Feb 2014 22:15, "Stephen J. Turnbull" <stephen at xemacs.org> wrote:
> Antoine Pitrou writes:
>  > On Sat, 22 Feb 2014 22:13:58 +1100
>  > Chris Angelico <rosuav at gmail.com> wrote:
>  > > hasattr(x,"y") <-> (x.y or True except AttributeError: False)
>  > But it's not the same. hasattr() returns a boolean, not an arbitrary
>  > value.
> I think he meant
>     hasattr(x,"y") <-> (x.y and True except AttributeError: False)

With PEP 463, the explicit equivalent of hasattr() would be something like :

hasattr(x,"y") <-> (bool(x.y) or True except AttributeError: False)

The version Chris came up with was close, but as Antoine noted, didn't
ensure the result was always exactly True or False.

The translation isn't simple because we don't allow an "else" clause on the
except expression (and I agree with this limitation), so the first
expression needs to be one that will *evaluate* x.y, but ensure the result
of the expression is True if no exception is thrown.

However, as Chris noted in his reply, there are still cases where using
hasattr makes more sense, so the fact it *can* be written as an except
expression instead is a curiosity rather than anything with deep practical


P.S. The fully general variant of "else" emulation under PEP 463:

((bool(EXPR) and False) or NO_EXC_RESULT except EXC: EXC_RESULT)

Note: never actually use this, it's effectively unreadable ;)

> Python-Dev mailing list
> Python-Dev at python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe:
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20140223/d8d36ac1/attachment-0001.html>

More information about the Python-Dev mailing list