[Python-ideas] Make "raise" an expression
אלעזר
elazarg at gmail.com
Sat Aug 6 19:24:09 EDT 2016
The raise statement cannot be used as an expression, even though there is
no theoretical reason for it not to. I don't see any practical reason
either - except the fact that it requires changing the syntax.
I have found this idea mentioned by Anthony Lee in a thread from 2014,
regarding "or raise",
https://mail.python.org/pipermail/python-ideas/2014-November/029921.html. B
ut there is nothing against the idea there.
Yes, it could easily be implemented using a function, but this seems to be
an argument against *augmenting* the language, not against *changing* it.
Moreover, this function will have uglier name, since `raise` is taken. (It
could have been the other way around - omitting the statement entirely,
leaving only a built in function `raise()`. I'm not suggesting that, of
course)
As mentioned there, it does add a single line in the traceback - which is
not immediately what you are looking for.
Python's tendency towards explicit control flow is irrelevant in this case.
An exception can already be raised from anywhere, at any time, and there's
no way see it from the source code (unlike e.g. break/continue).
Such a change will (only) break external tools that use the ast module, or
tools analyzing Python code that uses this feature. This happens at every
language change, so it can be done together with the next such change.
Use cases:
result = f(args) or raise Exception(...)
result = f(x, y) if x > y else raise Exception(...)
f(lambda x: max(x, 0) or raise Exception(...))
d = defaultdict(list)
...
d[v] or raise KeyError(v)
try:
return foo()
except:
return try_bar() or raise
To be honest, I'm not sure that this change is worthwhile. Admittedly the
use cases are weak, and in some ways this is complementary of the (sadly
rejected) "except expression". I would still like to "finish that thought",
so - why not?
~Elazar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160806/466c175c/attachment-0001.html>
More information about the Python-ideas
mailing list