6.5. Exception Assertion

6.5.1. Rationale

  • Raises AssertionError if argument is False

  • Can have optional message

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

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

So if there is an error (value 4 is not a member of data), then the exception is raised.

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

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

6.5.2. Assertion of Sequences

>>> data = [1, 2, 3]
>>>
>>> assert type(data) is list
>>> assert all(type(x) is int for x in data)
>>> import sys
>>>
>>> assert sys.version_info >= (3, 9)
>>> assert sys.version_info >= (3, 9), 'Python 3.9+ required'

6.5.3. Assignments

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

English:
    1. Use data from "Given" section (see below)
    2. Check value passed to a `check` function
        a. Check if `version` is greater or equal to `REQUIRED_VERSION`
        b. If not, raise exception with message 'Python 3.7+ required'
    3. Non-functional requirements
        a. Write solution inside `check` function
        b. Mind the indentation level
        c. Use `assert` kyword
    4. Compare result with "Tests" section (see below)

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Sprawdź poprawność wartości przekazanej do funckji `check`
        a. Sprawdź czy `version` jest większe lub równe `REQUIRED_VERSION`
        b. Jeżeli nie, podnieś wyjątek z komunikatem 'Python 3.7+ required'
    3. Wymagania niefunkcjonalne
        a. Rozwiązanie zapisz wewnątrz funkcji `check`
        b. Zwróć uwagę na poziom wcięć
        c. Użyj słowa kluczowego `assert`
    4. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Tests:
    >>> check( (3,6,0) )
    Traceback (most recent call last):
    AssertionError: Python 3.7+ required
    >>> check( (3,6,12) )
    Traceback (most recent call last):
    AssertionError: Python 3.7+ required
    >>> check( (3,7) )
    >>> check( (3,7,0) )
    >>> check( (3,7,1) )
    >>> check( (3,8) )
    >>> check( (3,9) )
    >>> check( (3,10) )
"""

# Given
REQUIRED_VERSION = (3, 7)


def check(version):
    ...