An Assert is to check -
1. the valid condition,
2. the valid statement,
3. true logic;
of source code. Instead of failing the whole project it gives an alarm that something is not appropriate in your source file.
In example 1, since variable 'str' is not null. So no any assert or exception get raised.
Example 1:
#!/usr/bin/pythonstr = 'hello Python!'strNull = 'string is Null'if __debug__: if not str: raise AssertionError(strNull)print strif __debug__: print 'FileName '.ljust(30,'.'),(__name__) print 'FilePath '.ljust(30,'.'),(__file__)------------------------------------------------------Output:hello Python!FileName ..................... helloFilePath ..................... C:/Python\hello.py
In example 2, var 'str' is null. So we are saving the user from going ahead of faulty program by assert statement.
Example 2:
#!/usr/bin/pythonstr = ''strNull = 'NULL String'if __debug__: if not str: raise AssertionError(strNull)print strif __debug__: print 'FileName '.ljust(30,'.'),(__name__) print 'FilePath '.ljust(30,'.'),(__file__)------------------------------------------------------Output:AssertionError: NULL String
The moment we don't want debug and realized the assertion issue in the source code. Disable the optimization flag
python -O assertStatement.py
nothing will get print