AssertionError signals that a condition expected to be true was false. It is raised by an assert statement, which checks a condition and stops execution when that condition fails. This makes assertions useful for validating assumptions before later processing continues. section 3.6.2 section 3.6.4
Check an expected value
When two values should match, an assertion makes that expectation explicit: num1 = 5 num2 = 10 assert num1 == num2 Because 5 does not equal 10, this statement produces an AssertionError. The exception identifies a failed condition rather than a syntax, import, index, key, or name problem. section 3.6.2 section 3.6.2
In a data workflow, assertions can protect downstream work. For example, after a database query, assert that the returned data has more than zero rows. If no rows are available, the AssertionError stops remaining processing instead of allowing later files or transformations to run on empty results. section 3.6.4 section 3.6.4
Add a useful failure message
Place a message after the condition to make a failed check easier to investigate: assert customer_key_features.shape[0] > 0, "Empty data returned" A false condition raises AssertionError with the supplied message. Use assert when AssertionError is the appropriate failure type; use raise when a different error type is needed. section 3.6.4 section 3.6.4
Listing 3.43 This time we use a try/except block to handle the AssertionError that arises when an invalid stock ticker is passed to the web request. The exception block here will bypass the error, tracking the stock ticker in a failures list, and the code execution will proceed to the next ticker in the list (rather than exiting the loop with an error). You can run this code yourself using ch3’s download_tech_stock_prices_including_error_handling.py file.
all_data = {} #1
failures = [] #2
for ticker in tickers: #3
try: #4
all_data[ticker] = si.get_data(ticker) #4
print(ticker + " downloaded SUCESSFULLY") #4
except AssertionError: #5
failures.append(ticker) #5
print(ticker + " download FAILED") #5
A try/except block can catch an AssertionError from an invalid ticker, record that ticker as failed, and continue downloading data for later valid tickers. section 3.6.3
Catching AssertionError can keep a batch job moving while preserving failures for review. In the ticker-download workflow, a fake symbol raises the exception; the exception handler adds it to a failures list and the loop proceeds to the next symbol. A broader except Exception handler can catch other error types too, while finally runs whether an error occurs or not. section 3.6.3 section 3.6.3
