Thursday, April 24, 2008

"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?


regebro said...

Or if you need to raise an exception maybe you could actually create a named function and use it instead of the lambda? :)

You don't *have* to write 500 character lines just because you can, you know. ;)

siddhi said...

Or maybe lambda can become more expressive, allowing multiple lines and statements within it [ I know, its not happening :( ]

regebro said...

Why on earth would you want that!?

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.

Alexander Kozlovsky said...

Well, maybe I don't quite understand the problem...

>>> def _raise(exc): raise exc
>>> r = lambda: _raise(TypeError("My error text"))
>>> r()
Traceback (most recent call last):
TypeError: My error text

Jack Diederich said...

Oh dear. Raise is a statement because .. raise is a statement. Statements can't be on the right side of other statements. What on God's green earth would the following mean?

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?