"raise" becomming a function in py3k?
Over on the voidspace blog, there is a little discussion about raising an exception in a lambda.
Because raise is a statement, it's kind of a hard thing to do. Raising an exception as an expression that is.
Which "raises" the question, why isn't raise a function in py3k?
The two suggestions on how to raise in an expression were these:
>>> r = lambda: eval(compile("raise RuntimeError", '', 'exec'))
>>> r()
>>> ctypes.pythonapi.PyErr_SetObject(*map(ctypes.py_object, (e.__class__, e)))
Which are kind of both a bit yuk.
So maybe raise could be a bit more expressive in py3k?
Because raise is a statement, it's kind of a hard thing to do. Raising an exception as an expression that is.
Which "raises" the question, why isn't raise a function in py3k?
The two suggestions on how to raise in an expression were these:
>>> r = lambda: eval(compile("raise RuntimeError", '', 'exec'))
>>> r()
>>> ctypes.pythonapi.PyErr_SetObject(*map(ctypes.py_object, (e.__class__, e)))
Which are kind of both a bit yuk.
So maybe raise could be a bit more expressive in py3k?
Comments
You don't *have* to write 500 character lines just because you can, you know. ;)
Then lambdas would get the same functionality as a function, and use the same syntax as a function, and you would need a return statement, just like a function. Then why not just use a function?
I don't get the fixation with lambdas. They are just anonymous functions. It's perfectly possible to use a non-anonymous function instead. The only reason to use lambdas is to save one line of code.
>>> def _raise(exc): raise exc
...
>>> r = lambda: _raise(TypeError("My error text"))
>>> r()
Traceback (most recent call last):
...
TypeError: My error text
e = Exception()
if raise(e): pass
while raise(e) or 7: pass
try: do_stuff()
except raise(e): pass
Sure you could make it a function and then have a coding convention that is only be used like a statement but then why not leave it as a statement in the first place?