Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Python's `assert` throw an exception that I choose

Can I make assert throw an exception that I choose instead of AssertionError?

UPDATE:

I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a Node object with certain arguments, it would check if the arguments were good for creating a node, and if not it would raise NodeError.

But I know that Python has a -o mode in which asserts are skipped, which I would like to have available because it would make my program faster. But I would still like to have my own exceptions. That's why I want to use assert with my own exceptions.

like image 936
Ram Rachum Avatar asked Oct 14 '09 21:10

Ram Rachum


People also ask

Does assert throw an exception Python?

The assert Statement When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception. If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.

How do you trigger an exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

How do I make an assertion in Python?

Syntax for using Assert in Pyhton: In Python we can use assert statement in two ways as mentioned above. assert statement has a condition and if the condition is not satisfied the program will stop and give AssertionError . assert statement can also have a condition and a optional error message.


2 Answers

This will work. But it's kind of crazy.

try:     assert False, "A Message" except AssertionError, e:     raise Exception( e.args ) 

Why not the following? This is less crazy.

if not someAssertion: raise Exception( "Some Message" ) 

It's only a little wordier than the assert statement, but doesn't violate our expectation that assert failures raise AssertionError.

Consider this.

def myAssert( condition, action ):     if not condition: raise action 

Then you can more-or-less replace your existing assertions with something like this.

myAssert( {{ the original condition }}, MyException( {{ the original message }} ) ) 

Once you've done this, you are now free to fuss around with enable or disabling or whatever it is you're trying to do.

Also, read up on the warnings module. This may be exactly what you're trying to do.

like image 72
S.Lott Avatar answered Sep 25 '22 00:09

S.Lott


How about this?

 >>> def myraise(e): raise e ...  >>> cond=False >>> assert cond or myraise(RuntimeError) Traceback (most recent call last):   File "", line 1, in    File "", line 1, in myraise RuntimeError  
like image 42
John La Rooy Avatar answered Sep 22 '22 00:09

John La Rooy