An assertion is a short Python check for a condition that must be true. Write `assert condition`; if the condition is false, Python raises an `AssertionError`. Assertions are useful when continuing would make later work invalid or misleading. section 3.6.2 section 3.9
Use an assertion to protect a data workflow assumption. For example, after querying a database, check that the returned data has at least one row before cleaning it, building features, or running later files. A failed check stops execution immediately and alerts the user instead of allowing downstream processing to continue with empty data. section 3.6.4 section 3.9
Check that a query returned data
A data-processing function can require a nonempty result: `customer_key_features = pd.read_sql(conn, query)` `assert customer_key_features.shape[0] > 0` If the query returns zero rows, the assertion raises `AssertionError`. Add a comma and message when the failure needs a clearer explanation: `assert customer_key_features.shape[0] > 0, "Empty data returned"`. section 3.6.4 section 3.6.4
Choose between `assert` and `raise` based on the error behavior you need:
- Use `assert` for a concise validation check when an `AssertionError` is acceptable. section 3.6.4
- Use `raise` when the situation needs a particular Python error type, because `raise` can produce more than `AssertionError`. section 3.6.4
- Use assertions in unit tests to check that a function produces the expected result for given inputs. section 10.1.1
Listing 3.49 In this listing, we modify the earlier code to use an assert statement that checks for whether non-zero rows are returned from the customer data table.. This code is available in the read_from_customer_database_with_assert.py ch3 file.
def process_data(): #1
customer_key_features = pd.read_sql(conn, #2
"""SELECT churn, #2
total_day_charge, #2
total_intl_minutes, #2
number_customer_service_calls #2
FROM customer_data""") #2
assert customer_key_features.shape[0] > 0 #3
[...additional code] #4
This listing places an assertion directly after a database query, illustrating a practical guard against an empty dataset. section 3.6.4
Assertions also support testing. They are single-line checks of whether a condition is true and can verify the validity of a condition in a Python function. In a unit test, that can mean checking whether a function returns the expected value for a set of inputs. section 10.1.1 section 10.1.1

















