[Python-ideas] raise in lambda

Chris Angelico rosuav at gmail.com
Tue Nov 28 14:09:33 EST 2017


On Wed, Nov 29, 2017 at 6:03 AM, Soni L. <fakedme+py at gmail.com> wrote:
> Would be useful to pass exception-raising lambdas around.
>
> ensure(cond, lambda: raise TypeError())
>
> I guess one could instead use (and raise in ensure())
>
> ensure(cond, lambda: TypeError())
>
> But I think exception-raising lambdas would be nicer.

You can easily create a throw() function:

def throw(exc):
    raise exc

Then you can use that in your lambda function:

ensure(cond, lambda: throw(TypeError("...")))

However, before you jump onto the "let's construct this lazily" idea,
benchmark the cost of creating a lambda function. It's more expensive
than a lot of people realize, and if all you save is a bit of string
formatting, you may as well just eagerly format that string.

ChrisA


More information about the Python-ideas mailing list