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?
The assert
statement exists in almost every programming language. When you do...
assert condition
... you're telling the program to test that condition, and trigger an error if the condition is false.
In Python, it's roughly equivalent to this:
if not condition: raise AssertionError()
Try it in the Python shell:
>>> assert True # nothing happens >>> assert False Traceback (most recent call last): File "", line 1, in AssertionError
Assertions can include an optional message, and you can disable them when you're done debugging. See here for the relevant documentation.
Watch out for the parentheses. As has been pointed out above, in Python 3, assert
is still a statement, so by analogy with print(..)
, one may extrapolate the same to assert(..)
or raise(..)
but you shouldn't.
This is important because:
assert(2 + 2 == 5, "Houston we've got a problem")
won't work, unlike
assert 2 + 2 == 5, "Houston we've got a problem"
The reason the first one will not work is that bool( (False, "Houston we've got a problem") )
evaluates to True
.
In the statement assert(False)
, these are just redundant parentheses around False
, which evaluate to their contents. But with assert(False,)
the parentheses are now a tuple, and a non-empty tuple evaluates to True
in a boolean context.
As other answers have noted, assert
is similar to throwing an exception if a given condition isn't true. An important difference is that assert statements get ignored if you compile your code with the optimization option. The documentation says that assert expression
can better be described as being equivalent to
if __debug__: if not expression: raise AssertionError
This can be useful if you want to thoroughly test your code, then release an optimized version when you're happy that none of your assertion cases fail - when optimization is on, the __debug__
variable becomes False and the conditions will stop getting evaluated. This feature can also catch you out if you're relying on the asserts and don't realize they've disappeared.
Others have already given you links to documentation.
You can try the following in a interactive shell:
>>> assert 5 > 2 >>> assert 2 > 5 Traceback (most recent call last): File "", line 1, in builtins.AssertionError:
The first statement does nothing, while the second raises an exception. This is the first hint: asserts are useful to check conditions that should be true in a given position of your code (usually, the beginning (preconditions) and the end of a function (postconditions)).
Asserts are actually highly tied to programming by contract, which is a very useful engineering practice:
The goal of an assertion in Python is to inform developers about unrecoverable errors in a program.
Assertions are not intended to signal expected error conditions, like “file not found”, where a user can take corrective action (or just try again).
Another way to look at it is to say that assertions are internal self-checks in your code. They work by declaring some conditions as impossible in your code. If these conditions don’t hold that means there’s a bug in the program.
If your program is bug-free, these conditions will never occur. But if one of them does occur the program will crash with an assertion error telling you exactly which “impossible” condition was triggered. This makes it much easier to track down and fix bugs in your programs.
Here’s a summary from a tutorial on Python’s assertions I wrote:
Python’s assert statement is a debugging aid, not a mechanism for handling run-time errors. The goal of using assertions is to let developers find the likely root cause of a bug more quickly. An assertion error should never be raised unless there’s a bug in your program.
The assert statement has two forms.
The simple form, assert
, is equivalent to
The extended form, assert
, is equivalent to
Assertions are a systematic way to check that the internal state of a program is as the programmer expected, with the goal of catching bugs. See the example below.
>>> number = input('Enter a positive number:') Enter a positive number:-1 >>> assert (number > 0), 'Only positive numbers are allowed!' Traceback (most recent call last): File "", line 1, in AssertionError: Only positive numbers are allowed! >>>
From docs:
Assert statements are a convenient way to insert debugging assertions into a program
Here you can read more: http://docs.python.org/release/2.5.2/ref/assert.html
Here is a simple example, save this in file (let's say b.py)
def chkassert(num): assert type(num) == int chkassert('a')
and the result when $python b.py
Traceback (most recent call last): File "b.py", line 5, in chkassert('a') File "b.py", line 2, in chkassert assert type(num) == int AssertionError
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.:
assert 1>0 #normal execution assert 0>1 #Traceback (most recent call last): #File "", line 1, in #assert 0>1 #AssertionError
def getUser(self, id, Email): user_key = id and id or Email assert user_key
Can be used to ensure parameters are passed in the function call.
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:
def KelvinToFahrenheit(Temperature): assert (Temperature >= 0),"Colder than absolute zero!" return ((Temperature-273)*1.8)+32 print KelvinToFahrenheit(273) print int(KelvinToFahrenheit(505.78)) print KelvinToFahrenheit(-5)
When the above code is executed, it produces the following result:
32.0 451 Traceback (most recent call last): File "test.py", line 9, in print KelvinToFahrenheit(-5) File "test.py", line 4, in KelvinToFahrenheit assert (Temperature >= 0),"Colder than absolute zero!" AssertionError: Colder than absolute zero!
Shortcuts to grok 'assert'.
assert
performs as a Checkpoint,
If it functions well, continue;
otherwise raise an alert.
>>>this_is_very_complex_function_result = 9 >>>c = this_is_very_complex_function_result >>>test_us = (c >> #first we try without assert >>>if test_us == True: print("YES! I am right!") else: print("I am Wrong, but the program still RUNS!") I am Wrong, but the program still RUNS! >>> #now we try with assert >>> assert test_us Traceback (most recent call last): File "", line 1, in assert test_us AssertionError >>>
Basically the assert keyword meaning is that if the condition is not true then it through an assertionerror else it continue for example in python.
code-1
a=5 b=6 assert a==b
OUTPUT:
assert a==b AssertionError
code-2
a=5 b=5 assert a==b
OUTPUT:
Process finished with exit code 0