tags:

views:

91

answers:

3

Hi Folks,

I have the following code:

def causes_exception(lamb):
    try:
       lamb()
       return False
    except:
       return True

I was wondering if it came already in any built-in library?

Ya'ir

Edit: Thx for all the commentary. It's actually impossible to detect whether code causes an exception without running it -- otherwise you could solve the halting problem (raise an exception if the program halts). I just wanted a syntactically clean way to filter a set of identifiers for those where the code didn't except.

+2  A: 

I'm not aware of that function, or anything similar, in the Python standard library.

It's rather misleading - if I saw it used, I might think it told you without calling the function whether the function could raise an exception.

RichieHindle
I agree. Not that i've ever encountered such a method.
Josiah
+7  A: 

No, as far as I know there is no such function in the standard library. How would it be useful? I mean, presumably you would use it like this:

if causes_exception(func):
    # do something
else:
    # do something else

But instead, you could just do

try:
    func()
except SomeException:
    # do something else
else:
    # do something
dF
+4  A: 

There's assertRaises(exception, callable) in unittest module and this is probably the only place where such check makes sense.

In regular code you can never be 100% sure that causes_exception you suggested are not causing any side effects.

Alex Lebedev