eg x = "hello". Instead of doing assert x == "hello", can I not do a if x != "hello". Is using assert more pythonic?
According to the documentation, assert x == "hello"
is equivalent to
if __debug__:
if not (x == "hello"):
raise AssertionError
__debug__
is a read-only variable that is set to True
if Python is not run with the -O
flag, and the compiler can omit the assertion check altogether when -O
is used (rather than constantly checking the value of __debug__
at run-time).
Use assertions for debugging and testing, to quickly end your program if an assertion fails. Use if
statements for code that must run to enable the rest of your code to work properly.