Python-Ref > Basic usage > Debugging > Call stack
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Call stack

Which function called which when an error occured
Simple errors like division by zero or undefined variables that occur directly in you code give you just the information about the place where the error is present. However in presence of functions and modules, the error might occur in a different function than the one that is currently executed. In this case Python error messages give you the whole "stack" of function calls at the time of the crash (the exception in an inner function traverses this stack from bottom up and only if not caught causes an error).
In the following example the exception is thown in a function _compile in the module sre. You can see the functions that this function was called from and there location in the source files. As in simpler cases you are provided with the text of the corresponding line.
Expand/Shrink
Zdroj: (debug2-1.py)
  1   import re
  2   
  3   text = "hi there"
  4   m = re.search( "(.*)(hi)(.*))", text)
  5   print m.groups()
stderr:
Traceback (most recent call last):
  File "debug2-1.py", line 4, in ?
    m = re.search( "(.*)(hi)(.*))", text)
  File "/usr/lib/python2.4/sre.py", line 134, in search
    return _compile(pattern, flags).search(string)
  File "/usr/lib/python2.4/sre.py", line 227, in _compile
    raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis
Doba běhu: 37.5 ms
The call stack in this case was line 4 in your source -> function search on line 134 in sre.py -> function _compile on line 227 in sre.py
Again the message gives you a pretty good information about the source of the problem "unbalanced parenthesis" - there is a missing or extra closing parenthesis.
The following example demonstrates the same thing, this time with custom made functions.
Expand/Shrink
Zdroj: (debug2-2.py)
  1   def multiply_list( xs):
  2     ret = 1
  3     for x in xs:
  4       ret *= x
  5     return ret
  6   
  7   def geometric_mean( xs):
  8     return multiply_list( xs) ** (1.0/len( xs))
  9   
 10   print geometric_mean( [1,2,4])
 11   print geometric_mean( [None,2,4])
stdout:
2.0
stderr:
Traceback (most recent call last):
  File "debug2-2.py", line 11, in ?
    print geometric_mean( [None,2,4])
  File "debug2-2.py", line 8, in geometric_mean
    return multiply_list( xs) ** (1.0/len( xs))
  File "debug2-2.py", line 4, in multiply_list
    ret *= x
TypeError: unsupported operand type(s) for *=: 'int' and 'NoneType'
Doba běhu: 20.9 ms