Reputation: 421
What are the big differences between raise AssertionError
and assert
to build in a "fault"? What are the effects on the code? And is one or the other more pythonic in a way?
The reason for my question is because I am learning to program. Right now we have an exercise where for example when x != 0
we need to get an AssertionError
"false".
I looked this up online, where I found the following code:
if x != 0:
raise AssertionError ("false")
But my teachers also use the following a lot:
assert x == 0,"fout"
What are the (dis)advantages of each approach?
Thanks a lot in advance.
Upvotes: 20
Views: 27884
Reputation: 33275
Those two code examples are equivalent, with the exception that assert
statements can be globally disabled with the -O
command-line flag.
See:
# script.py
assert 0, "statement"
raise AssertionError("error")
Which produces different errors with and without the -O
flag:
$ python script.py
Traceback (most recent call last):
File "/tmp/script.py", line 1, in <module>
assert 0, "statement"
AssertionError: statement
$ python -O script.py
Traceback (most recent call last):
File "/tmp/script.py", line 2, in <module>
raise AssertionError("error")
AssertionError: error
Upvotes: 24