12.5. Exception Assertion

  • Raises AssertionError if argument is False

  • Can have optional message

  • Running Python with the -O optimization flag disables assert statements

>>> admins = ['mwatney', 'mlewis', 'rmartinez']
>>>
>>> assert 'avogel' in admins, 'You must be an admin to edit this page'
Traceback (most recent call last):
AssertionError: You must be an admin to edit this page

12.5.1. Assert Keyword

Note the output of the following statements:

>>> data = [1, 2, 3]
>>>
>>> 1 in data
True
>>> 4 in data
False

In both examples from above, the output is visible. We can intercept it to the variable, but we need to define it and store those values.

In the next example assert keywords allows to proceed with execution, if only the assertion is True.

>>> data = [1, 2, 3]
>>>
>>> assert 1 in data
>>>
>>> assert 4 in data
Traceback (most recent call last):
AssertionError

If the assertion is True (value 1 in a member of data) nothing will happen. However if there is an error (value 4 is not a member of data), then the exception (AssertionError) is raised.

Assertions can have additional information, which can help with debugging:

>>> data = [1, 2, 3]
>>>
>>> assert 4 in data, '4 must be in data'
Traceback (most recent call last):
AssertionError: 4 must be in data

12.5.2. Sequence Assertion

>>> data = [1, 2, 3]
>>>
>>> assert type(data) is list
>>> assert all(type(x) is int for x in data)

12.5.3. Use Case - 0x01

You can use assertions to check Python version.

>>> import sys
>>>
>>> assert sys.version_info >= (3, 11)
>>> assert sys.version_info >= (3, 11), 'Python 3.11+ required'

12.5.4. Assignments

Code 12.7. Solution
"""
* Assignment: Exception Assert Version
* Type: class assignment
* Complexity: easy
* Lines of code: 1 lines
* Time: 3 min

English:
    1. Check value passed to a `result` function:
        a. Check if `version` is greater or equal to `REQUIRED_VERSION`
        b. If not, raise exception with message 'Python 3.10+ required'
    2. Non-functional requirements:
        a. Write solution inside `result` function
        b. Mind the indentation level
        c. Use `assert` kyword
    3. Run doctests - all must succeed

Polish:
    1. Sprawdź poprawność wartości przekazanej do funckji `result`:
        a. Sprawdź czy `version` jest większe lub równe `REQUIRED_VERSION`
        b. Jeżeli nie, podnieś wyjątek z komunikatem 'Python 3.10+ required'
    2. Wymagania niefunkcjonalne:
        a. Rozwiązanie zapisz wewnątrz funkcji `result`
        b. Zwróć uwagę na poziom wcięć
        c. Użyj słowa kluczowego `assert`
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `assert`
    * `>=`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> result( (3,9,0) )
    Traceback (most recent call last):
    AssertionError: Python 3.10+ required
    >>> result( (3,9,12) )
    Traceback (most recent call last):
    AssertionError: Python 3.10+ required
    >>> result( (3,10) )
    >>> result( (3,10,0) )
    >>> result( (3,10,1) )
    >>> result( (3,11) )
    >>> result( (3,12) )
"""

REQUIRED_VERSION = (3, 10)


def result(version):
    ...


Code 12.8. Solution
"""
* Assignment: Exception Assert Types
* Type: class assignment
* Complexity: easy
* Lines of code: 2 lines
* Time: 5 min

English:
    1. Check value passed to a `add_numbers` function:
        a. assert that type of `a` or `b` is int or float
        b. if not, raise assertion error with message:
           'Parameter `a` must be int or float'
    2. Non-functional requirements:
        a. Write solution inside `add_numbers` function
        b. Mind the indentation level
        c. Use `assert` kyword
    3. Run doctests - all must succeed

Polish:
    1. Sprawdź poprawność wartości przekazanej do funckji `add_numbers`:
        a. zapewnij, że typ `a` oraz `b` jest int lub float
        b. jeżeli nie, podnieś błąd asercji z komunikatem:
           'Parameter `a` must be int or float'
    2. Wymagania niefunkcjonalne:
        a. Rozwiązanie zapisz wewnątrz funkcji `add_numbers`
        b. Zwróć uwagę na poziom wcięć
        c. Użyj słowa kluczowego `assert`
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `assert`
    * `isinstance()`
    * `type()`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> add_numbers(1, 0)
    1
    >>> add_numbers(0, 1)
    1
    >>> add_numbers(1.0, 0)
    1.0
    >>> add_numbers(0, 1.0)
    1.0
    >>> add_numbers('1', 0)
    Traceback (most recent call last):
    AssertionError: Parameter `a` must be int or float
    >>> add_numbers(0, '1')
    Traceback (most recent call last):
    AssertionError: Parameter `b` must be int or float
    >>> add_numbers([1], 0)
    Traceback (most recent call last):
    AssertionError: Parameter `a` must be int or float
    >>> add_numbers(0, [1])
    Traceback (most recent call last):
    AssertionError: Parameter `b` must be int or float
    >>> add_numbers(True, 0)
    Traceback (most recent call last):
    AssertionError: Parameter `a` must be int or float
    >>> add_numbers(0, False)
    Traceback (most recent call last):
    AssertionError: Parameter `b` must be int or float
"""

def add_numbers(a, b):
    return a + b


Code 12.9. Solution
"""
* Assignment: Exception Assert Len
* Type: class assignment
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

English:
    1. Check value passed to a `check` function:
        a. assert that argument `data` has length of 3
        b. if not, raise assertion error
    2. Non-functional requirements:
        a. Write solution inside `check` function
        b. Mind the indentation level
        c. Use `assert` kyword
    3. Run doctests - all must succeed

Polish:
    1. Sprawdź poprawność wartości przekazanej do funckji `check`:
        a. zapewnij, że argument `data` ma długość 3
        b. jeżeli nie, podnieś błąd asercji
    2. Wymagania niefunkcjonalne:
        a. Rozwiązanie zapisz wewnątrz funkcji `check`
        b. Zwróć uwagę na poziom wcięć
        c. Użyj słowa kluczowego `assert`
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `assert`
    * `len()`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> check([1, 2, 3, 4, 5])
    Traceback (most recent call last):
    AssertionError
    >>> check([1, 2, 3, 4])
    Traceback (most recent call last):
    AssertionError
    >>> check([1, 2, 3])
    >>> check([1, 2])
    Traceback (most recent call last):
    AssertionError
    >>> check([1])
    Traceback (most recent call last):
    AssertionError
    >>> check([])
    Traceback (most recent call last):
    AssertionError
"""

def check(data):
    ...


Code 12.10. Solution
"""
* Assignment: Exception Assert Set
* Type: class assignment
* Complexity: easy
* Lines of code: 1 lines
* Time: 3 min

English:
    1. Check value passed to a `check` function:
        a. assert that `data: set` contains numbers: 1, 2 and 3
        b. if not, raise assertion error
    2. Non-functional requirements:
        a. Write solution inside `check` function
        b. Mind the indentation level
        c. Use `assert` kyword
    3. Run doctests - all must succeed

Polish:
    1. Sprawdź poprawność wartości przekazanej do funckji `check`:
        a. zapewnij, że `data: set` ma liczby: 1, 2 i 3
        b. jeżeli nie, podnieś błąd asercji
    2. Wymagania niefunkcjonalne:
        a. Rozwiązanie zapisz wewnątrz funkcji `check`
        b. Zwróć uwagę na poziom wcięć
        c. Użyj słowa kluczowego `assert`
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `assert`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> check({1, 2, 3, 4, 5})
    Traceback (most recent call last):
    AssertionError
    >>> check({1, 2, 3, 4})
    Traceback (most recent call last):
    AssertionError
    >>> check({1, 2, 3})
    >>> check({1, 3, 2})
    >>> check({2, 1, 3})
    >>> check({2, 3, 1})
    >>> check({3, 1, 2})
    >>> check({3, 2, 1})
    >>> check({1, 2})
    Traceback (most recent call last):
    AssertionError
    >>> check({1, 3})
    Traceback (most recent call last):
    AssertionError
    >>> check({2, 1})
    Traceback (most recent call last):
    AssertionError
    >>> check({2, 3})
    Traceback (most recent call last):
    AssertionError
    >>> check({3, 1})
    Traceback (most recent call last):
    AssertionError
    >>> check({3, 2})
    Traceback (most recent call last):
    AssertionError
    >>> check({1})
    Traceback (most recent call last):
    AssertionError
    >>> check({2})
    Traceback (most recent call last):
    AssertionError
    >>> check({3})
    Traceback (most recent call last):
    AssertionError
"""

def check(data):
    ...