Asserts in Python

What is assert in python?

  • Enables Sanity checks in code
  • Checks if boolean conditions return true or false
  • With assert statement, if condition = true, the program can continue
  • With assert statement, if condition = false, program aborts and stops with optional error messages.
  • Asserts should be used in modertion. can slow down programs and better to disable in production code.

Python’s built-in functionality

Example 1

x = 5
assert x == 5

Example 2

my_list = [1,2,3,4,5]
assert all(my_list[i] <= mylist[i+1] for i in range(len(my_list)-1))

Example 3 Pipeline Validation

assert len(df.columns) == expected_num_columns, "Pipeline changed the number of columns unexpectedly"

Example 4 Model Input Assertion

assert len(features) == expected_num_features, "Input should have the expected number of features"

Example 5 Data Range Assertion

assert (df['price'] >= 0).all(), "Price should be non-negative"

Example 6 Data Integrity Assertion

assert (df['start_date'] <= df['end_date']).all(), "Start date should be before or equal to end date"
Previous
Next