11.5. Exception Assertion

11.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

11.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'

11.5.3. Assignments

Code 11.6. Solution
"""
* Assignment: Exception Assert Version
* Required: yes
* 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.7+ 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.7+ 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ść

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

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

REQUIRED_VERSION = (3, 7)


def result(version):
    ...