I have been reading some source code and in several places I have seen the usage of assert
.
What does it mean exactly? What is its usage?
I have been reading some source code and in several places I have seen the usage of assert
.
What does it mean exactly? What is its usage?
Python assert is basically a debugging aid which test condition for internal self-check of your code. Assert makes debugging really easy when your code gets into impossible edge cases. Assert check those impossible cases.
Let's say there is a function to calculate price of item after discount :
here, discounted_price can never be less than 0 and greater than actual price. So, in case the above condition is violated assert raises an Assertion Error, which helps the developer to identify that something impossible had happened.
Hope it helps :)
Can be used to ensure parameters are passed in the function call.
If you ever want to know exactly what a reserved function does in python, type in
help(enter_keyword)
Make sure if you are entering a reserved keyword that you enter it as a string.
if the statement after assert is true then the program continues , but if the statement after assert is false then the program gives an error. Simple as that.
e.g.:
format : assert Expression[,arguments] When assert encounters a statement,Python evaluates the expression.If the statement is not true,an exception is raised(assertionError). If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback. Example:
When the above code is executed, it produces the following result: