python assert和exception的区别

As for disabling them, when running python in optimized mode, where __debug__ is False, assert statements will be ignored. Just pass the -O flag:

python -O script.py

__debug__:如果程序运行时不带-O参数,则为True;反之则为False。
https://docs.python.org/3/reference/simple_stmts.html#assert

也就是, assert 可以在程序正式运行时关闭,只用于单元测试;exception是一定会报错。


参考:

  1. What is the use of “assert” in Python?;
  2. Python3 try-except、raise和assert解析

你可能感兴趣的:(python)