Table of Content
- What is Python assert Statement?
- Syntax for using Assert in Python:
- When to Use assert Statement in Python
- How to Use assert Statement in Python
- What are the Best Practices for Using assert in Python?
- Wrap Off
In programming, assertions are statements that proclaim a fact or logic that should most likely return true in your program.
They are boolean expressions that check if the conditions return true and do something when it is not true.
For example, when writing a function to handle a division, you are most likely to not allow the divisor to be zero. Therefore, you assert divisor is not equal to zero.
In most cases, it is used as a debugging tool, since it halts the program as soon as an error occurs and displays it.
In this article, you will learn about assertion statements in Python, when and how you can use them in your codes, and the best practices to follow when using assert statements in Python.
What is Python assert Statement?
The assert
statement in Python is a built-in statement that expresses an assertion condition in the program such that a condition or expression is always meant to be true.
The assert statements are a convenient way to insert debugging assertions into a program
If the condition is true, nothing happens, and it simply continues to execute the rest of the program.
If the condition is false, the assert statement in Python stops the program execution at that point and gives an AssertionError
.
The assert
statement takes an expression and optional message.
Note: assert in Python is a statement and not a function.
Syntax for using Assert in Python:
Here's the syntax for using assert in Python language:
The assert statement has two forms.
The simple form, assert <expression>
, is equivalent to
if __debug__:
if not <expression>: raise AssertionError
The extended form, assert <expression1>, <expression2>
, is equivalent to
if __debug__:
if not <expression1>: raise AssertionError(<expression2>)
When you do
assert condition
you're telling the program to test that condition, and immediately trigger an error if the condition is false.
In Python, it's roughly equivalent to this:
if not condition:
raise AssertionError()
The first syntax asserts the condition and returns the default error message when it fails to be true, while the second syntax asserts the condition and returns the custom error message when it fails.
Watch out for the parentheses when using assert in Python!
In Python 3, assert
is still a statement, so you should not use assert as you do with a function.
For instance,
This is wrong:
assert(1 + 1 == 2, "Correct")
This is correct:
assert 1 + 1 == 2, "Correct"
When to Use assert Statement in Python
In Python, we can use an assert
statement at different times, but here are the most common use cases.
- Use the
assert
statement to check data types of values, values of the argument, and the output of the function or logic. - Use the
assert
statement when you have a condition that is a tautology, i.e. it should always return true and if the condition is not satisfied, the program will stop and give anAssertionError
. - Use the
assert
statement to detect problems early in your program, where the cause is clear, rather than later when some other operation fails. A type error in Python, for example, can go through several layers of code before actually raising anException
if not caught early on. - Use the
assert
statement as documentation for other developers reading the code, who see theassert
and can confidently say that its condition holds from now on.
How to Use assert Statement in Python
Let's look at some examples of how to use an assert statement in Python.
How to Use an assert Statement to Check the Data Type of Value
In the above program, we created a function called mandatory_dict()
that takes a single value as an argument.
To test, we called the function with a variable that holds a dictionary. The assert statement passes and the function returns True.
Next, we called the function with another variable that holds an integer. The assert statement fails and gives an AssertionError
How to Use an assert Statement With a Custom Error Message
In the above program, when we call the function with another variable that holds an integer.
The assert statement fails and gives the error AssertionError: Value is not a dict
.
What are the Best Practices for Using assert in Python?
There are some caveats to see before using an assert statement in Python.
The aim to use assert
is on occasions when the program verifies a condition and returns a value that should stop the program immediately, instead of taking some alternative way to bypass the error.
Here are best practices on how to correctly use assert in Python:
1. Using Parentheses
As you may have noticed, the assert
statement optionally uses two conditions.
Hence, do not use parentheses to enclose the two conditions as one, for obvious advice.
If you do this:
assert (condition, message)
Example:
>>> assert (1==2, 1==1)
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
You will be running the assert
with a (condition, message)
which represents a tuple as the first parameter, and this happens because a non-empty tuple in Python is always True
.
However, you can do it separately without problem:
assert (condition), ("message")
Example:
>>> assert (1==2), ("This condition returns a %s value.") % "False"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: This condition returns a False value.
2. Debug purpose
If you are wondering when to use the assert
statement. Take an example used in real life:
- When your program tends to control each parameter entered by the user or whatever else:
def loremipsum(**kwargs):
kwargs.pop('bar') # return 0 if "bar" isn't in parameter
kwargs.setdefault('foo', type(self)) # returns `type(self)` value by default
assert (len(kwargs) == 0), "unrecognized parameter passed in %s" % ', '.join(kwargs.keys())
- Another case is in math when 0 or non-positive as a coefficient or constant on a certain equation:
def discount(item, percent):
price = int(item['price'] * (1.0 - percent))
print(price)
assert (0 <= price <= item['price']),\
"Discounted prices cannot be lower than 0 "\
"and they cannot be higher than the original price."
return price
- or even a simple example of a boolean implementation:
def true(a, b):
assert (a == b), "False"
return 1
def false(a, b):
assert (a != b), "True"
return 0
3. Data processing or data validation
Do not rely on the assert
statement to execute data processing or data validation because this statement can be turned off on the Python initialization with -O
or -OO
flag – meaning value 1, 2, and 0 (as default), respectively – or PYTHONOPTIMIZE
environment variable.
Value 1:
-
asserts are disabled;
-
bytecode files are generated using
.pyo
extension instead of.pyc
; -
sys.flags.optimize
is set to 1 (True
); -
and,
__debug__
is set toFalse
;
Value 2: disables one more stuff
- docstrings are disabled;
Therefore, using the assert
statement to validate a sort of expected data is extremely dangerous, implying even to some security issues.
Then, if you need to validate some permission, I recommend you raise AuthError
instead. As a precondition, an assert
is commonly used by programmers on libraries or modules that do not have direct user interaction.
Here is a nice example to tie it all together.
Let's assume you want to have a special number class in your code that represents positive integers called PositiveInt
.
Why would you want that?
You have many functions that use positive integers as parameters. By using PositiveInt
in your code, you don't have to check again and again in every function whether the input is valid.
It is guaranteed by PositiveInt
. A crude implementation looks like this
class PositiveInt(int):
# int is immutable, so we have to override new and not init
def __new__(cls, value):
if value <= 0:
raise ValueError(f"{value} is not positive")
assert value > 0, "value must be positive"
return super(PositiveInt, cls).__new__(cls, value)
Wrap Off
Assertions in Python are the condition or boolean expressions that are always supposed to be true in the code.
The assert
in Python statement takes an expression and optional message.
The assert
statement is used to check types, values of argument, and the output of the function.
The assert
statement can also be used as a debugging tool, as it halts the program at the point where an error occurs.
If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.
Please share this post and for more insightful posts on business, technology, engineering, history, and marketing, subscribe to our newsletter.