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.
This will work. But it’s kind of crazy.
Why not the following? This is less crazy.
It’s only a little wordier than the
assertstatement, but doesn’t violate our expectation that assert failures raiseAssertionError.Consider this.
Then you can more-or-less replace your existing assertions with something like this.
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.