Explaning the Assert Keyword as Used in Python Scripts and Not in Unit Tests

The aim of this page📝 is to explain and illustrate the use of "assert" statement in Python

Pavol Kutaj
2 min readSep 12, 2022

1. EXPLANATION

  • Adopted from

https://stackoverflow.com/questions/5142418/what-is-the-use-of-assert-in-python

  • The assert statement exists in almost every programming language.
  • It has two main uses:
  1. It helps 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 an Exception if not caught early on
  2. It works as documentation for other developers reading the code, who see the assert and can confidently say that its condition holds from now on.
  • 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()
  • Try it in the Python shell:
>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
  • Assertions can include an optional message, and you can disable them when running the interpreter
assert False, "Oh no! This assertion failed!"
  • Do not use parenthesis to call assert like a function: It is a statement.
  • If you do assert(condition, message) you'll be running the assert with a (condition, message) tuple as first parameter.
  • As for disabling them, when running python in optimized mode, where __debug__ is False, assert statements will be ignored.
  • Just pass the -O flag:
python -O script.py

2. EXAMPLE

  • assert belows tests if the HTTP requests for fetching the history of a Slack channel was succeded and it interrupts the program in case anythine else than ok is returned
import os
import slack

CHANNEL = os.environ['SLACK_CHANNEL']
MESSAGES_PER_PAGE = 200
client = slack.WebClient(token=os.environ['SLACK_TOKEN'])
page = 1
print("Retrieving page {}".format(page))
response = client.conversations_history(
channel=CHANNEL,
limit=MESSAGES_PER_PAGE,
)
assert response["ok"]
messages_all = response['messages']

3. LINKS

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com