Python-Ref > Basic usage > Debugging > Using assert statements
 
 

<-^^
Moduly
Knihovní funkce

Using assert statements

In larger projects, it is very useful to adopt a defensive approach to handling data. This means for example that we try to handle all possible spots where something might get wrong and try to catch erroneous data as soon as possible and report them back. One of the tools that enables us to do this is the assert statement.
Using this statement we specify conditions that we expect to be fulfilled at execution time for our code to run properly. Using this tool does not get rid of problems, it can however help to indetify them earlier and is especially useful during development.
The following code shows an example that naively accepts any input and then chokes on it.
Expand/Shrink
Zdroj: (debug5-1.py)
  1   import math
  2   
  3   def vector_length( vector):
  4     """this function calculates length of a 3D vector,
  5     vector should therefore be a sequence of 3 numbers"""
  6     x,y,z = vector
  7     return math.sqrt( x**2 + y**2 + z**2)
  8   
  9   print vector_length( [1,2,3])
 10   print vector_length( (0,2,0))
 11   print vector_length( [1,2])
 12     
stdout:
3.74165738677
2.0
stderr:
Traceback (most recent call last):
  File "debug5-1.py", line 11, in <module>
    print vector_length( [1,2])
  File "debug5-1.py", line 6, in vector_length
    x,y,z = vector
ValueError: need more than 2 values to unpack
Doba běhu: 18.9 ms
At first glance, we are not much better off - this program chokes on invalid data as well. However the conditions that must be met are expressed explicitly and before we try to handle the data. This is especially useful if the code is long and tricky to grasp.
Expand/Shrink
Zdroj: (debug5-2.py)
  1   import math
  2   
  3   def vector_length( vector):
  4     """this function calculates length of a 3D vector,
  5     vector should therefore be a sequence of 3 numbers"""
  6     # below we express our assertion that the supplied data is of length 3;
  7     # if this assertion is not true, our code does not work 
  8     assert len( vector) == 3
  9     x,y,z = vector
 10     return math.sqrt( x**2 + y**2 + z**2)
 11   
 12   print vector_length( [1,2,3])
 13   print vector_length( (0,2,0))
 14   print vector_length( [1,2])
 15     
stdout:
3.74165738677
2.0
stderr:
Traceback (most recent call last):
  File "debug5-2.py", line 14, in <module>
    print vector_length( [1,2])
  File "debug5-2.py", line 8, in vector_length
    assert len( vector) == 3
AssertionError
Doba běhu: 20.6 ms