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

Viewed 50923

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.

8 Answers

If you want to use asserts for this, this seems to work pretty well:

>>> def raise_(e): raise e
...
>>> x = -2
>>> assert x >= 0, raise_(ValueError('oops'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in raise_
ValueError: oops

Note that in the assert, the stuff after the comma will only be evaluated if the condition is false, so the ValueError will only be created and raised when needed.

Related