assert
In Python, the assert
keyword lets you create assertions to test whether a given condition is true. If the condition is false, then assert
raises an AssertionError
exception, optionally with a descriptive error message. Assertions are sanity checks into your code that help you identify bugs during development.
Python assert
Keyword Examples
Here’s a quick example to illustrate how to use the assert
keyword:
>>> x = 5
>>> y = 10
>>> assert x < y, "x is not less than y"
In this example, the condition x < y
is true, so assert
passes without raising an error. If x
had been greater than or equal to y
, the assert
would have raised an error:
>>> x = 15
>>> assert x < y, "x is not less than y"
Traceback (most recent call last):
...
AssertionError: x is not less than y
Because x
is greater than y
, the assertion fails and raises an AssertionError
exception with the specified message.
Python assert
Keyword Use Cases
- Quickly verifying assumptions made in your code during debugging
- Ensuring that your program is working as expected during development by inserting sanity checks
- Validating that certain conditions hold true during code testing
Related Resources
Tutorial
Python's assert: Debug and Test Your Code Like a Pro
In this tutorial, you'll learn how to use Python's assert statement to document, debug, and test code in development. You'll learn how assertions might be disabled in production code, so you shouldn't use them to validate data. You'll also learn about a few common pitfalls of assertions in Python.
For additional information on related topics, take a look at the following resources:
- Effective Python Testing With pytest (Tutorial)
- Using Python's assert to Debug and Test Your Code (Course)
- Testing Your Code With pytest (Course)
- Effective Testing with Pytest (Quiz)