Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Using Assertions in Python: Debugging and Ensuring Code Integrity | Mastering Error Handling in Python
Python Advanced Concepts

book
Using Assertions in Python: Debugging and Ensuring Code Integrity

In Python, the assert statement is a built-in feature designed to verify that specific conditions are true within your code. It serves as a sanity check, confirming that certain prerequisites are met at specific points during program execution.

The syntax for the assert statement is as follows:

python
assert condition, message

In Python, assertions are carried out by the assert statement. An assertion checks a condition, and if the condition evaluates to False, it raises an AssertionError exception with an optional error message.

def calculate_average(grades):
assert len(grades) > 0, "List of grades cannot be empty"
return sum(grades) / len(grades)

calculate_average([]) # Throw an error
12345
def calculate_average(grades): assert len(grades) > 0, "List of grades cannot be empty" return sum(grades) / len(grades) calculate_average([]) # Throw an error
copy

In this example, the function calculates the average grade, and the assertion ensures that the list of grades is not empty before calculating the average. If grades are empty, the assertion fails, preventing division by zero and indicating a clear error in program logic.

Here are some commonly utilized categories of assertions:

  • Value Assertions: These assertions are often employed in debugging and testing scenarios to verify that the values utilized in a program meet the expected criteria. For example, you might use assertions like assert x >= 18 or as previously illustrated, assert len(grades) > 0;

  • Type Assertions: Type assertions are especially valuable in dynamically typed languages like Python, where the type of a variable may shift. For instance, using assert isinstance(x, int) confirms that x is indeed an integer;

  • Collection Assertions: These assertions are used to check whether a collection (like a list or dictionary) includes particular elements or meets specific criteria. Examples include assert item in my_list or assert key in my_dict;

  • Exception Assertions: These are predominantly used in unit testing (which we will learn in the last section) to ensure that code correctly handles exceptions. For example, assert_raises(ValueError, int, 'abc') checks that converting 'abc' to an integer raises a ValueError. Similarly, assert_raises(ExceptionType, my_function, arg1, arg2) verifies that calling my_function with arg1 and arg2 raises an exception of type ExceptionType.

Now, let’s implement assertions in an existing project to verify certain conditions are met during the program’s execution.

Завдання

Swipe to start coding

Add assertions to a sample project that manages user data, ensuring that user information meets certain criteria.

  1. Check that the user_id is not already in the users dictionary to avoid duplicates;
  2. Ensure that user_id is an integer, maintaining consistency in user ID types;
  3. Confirm that user_info is passed as a dictionary to prevent data type errors.

Рішення

# Existing function to add user details
def add_user(users, user_id, user_info):
assert user_id not in users, "User ID already exists"
assert isinstance(user_id, int), "User ID must be an integer"
assert isinstance(user_info, dict), "User info must be a dictionary"

users[user_id] = user_info
print(f"Added user {user_id}")

# Test the function
users = {}
add_user(users, 1, {"name": "John", "age": 28})
add_user(users, 2, {"name": "Jane", "age": 32})
# The following will raise an assertion error
add_user(users, 1, {"name": "Alice", "age": 24}) # Duplicate user ID

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 4
# Existing function to add user details
def add_user(users, user_id, user_info):
___ user_id not ___ users, "User ID already exists"
___ isinstance(user_id, int), "User ID must be an integer"
___ ___(user_info, dict), "User info must be a dictionary"

users[user_id] = user_info
print(f"Added user {user_id}")

# Test the function
users = {}
add_user(users, 1, {"name": "John", "age": 28})
add_user(users, 2, {"name": "Jane", "age": 32})
# The following will raise an assertion error
add_user(users, 1, {"name": "Alice", "age": 24}) # Duplicate user ID

Запитати АІ

expand
ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

some-alt