I didn't have much basic information, so make a note.
Throws an exception when the conditional expression is not True. If you prepare this, you will be able to quickly notice when the code that worked properly until then suddenly behaves differently than expected while you are playing with it. If you just need to say "stop if it's not what you expected", it's convenient because you don't have to write a test class such as unittest. In ** machine learning and data analysis **, there are many parts where specifications have not been decided and trial and error is required, and there are quite a few ad hoc responses, so I think that writing tests is not always familiar. .. I would especially like to recommend it in such areas.
The syntax is as follows:
assert conditional expression,Message to be output when the conditional expression is False
If the conditional expression is `False```, then the exception ```AssertionError``` is thrown. If the conditional expression is
True
``, nothing happens.
>>> kitai = 100
>>> input = 1
>>> assert kitai == input, 'Expected value[{0}],Input value[{1}]'.format(kitai, input)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError:Expected value[100],Input value[1]
If you handle exceptions properly, it looks like this.
>>> try:
... kitai = 100
... input = 1
... assert kitai == input, 'Expected value[{0}],Input value[{1}]'.format(kitai, input)
... except AssertionError as err:
... print('AssertionError :', err)
...
AssertionError :Expected value[100],Input value[1]
The assert statement is executed only when the built-in constant `__debug__``` is
True```. This is the state if nothing is done. Adding `` -O``` to the command line option when running a Python script will change ``
debug to `` `False
and invalidate the assert statement.
Python3.6 official documentation
-7.3. assert
statement
-3. Built-in constant __debug__
-1. Command line and environment -O
option
Recommended Posts