使Python的“assert”抛出一个我选择的异常 [英] Making Python's `assert` throw an exception that I choose
问题描述
我可以使 assert
抛出一个我选择的异常,而不是 AssertionError
?
Can I make assert
throw an exception that I choose instead of AssertionError
?
更新:
我会解释我的动机:到目前为止,我已经有断言风格测试引起了我自己的例外;例如,当您使用某些参数创建一个 Node
对象时,它会检查参数是否适合创建一个节点,如果不是,则会引发 NodeError
。
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
.
但是我知道Python有一个 -o
模式,其中断言被跳过,我想提供,因为它会使我的程序更快。但我仍然希望有自己的例外。这就是为什么我要用自己的例外来使用断言。
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.
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" )
这只是一个比 assert
声明更小的一点,但不违反我们的期望
It's only a little wordier than the assert
statement, but doesn't violate our expectation that assert failures raise AssertionError
.
考虑这一点。
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.
另外,一个href =http://docs.python.org/library/warnings.html =noreferrer> warnings 模块。这可能正是你想要做的。
Also, read up on the warnings module. This may be exactly what you're trying to do.
这篇关于使Python的“assert”抛出一个我选择的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!