Python-Ref > Basic usage > Debugging > Call stack

Klíčová slova
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.
Zdroj: (
  1   import re
  3   text = "hi there"
  4   m = "(.*)(hi)(.*))", text)
  5   print m.groups()
Traceback (most recent call last):
  File "", line 4, in ?
    m = "(.*)(hi)(.*))", text)
  File "/usr/lib/python2.4/", line 134, in search
    return _compile(pattern, flags).search(string)
  File "/usr/lib/python2.4/", 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 -> function _compile on line 227 in
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.
Zdroj: (
  1   def multiply_list( xs):
  2     ret = 1
  3     for x in xs:
  4       ret *= x
  5     return ret
  7   def geometric_mean( xs):
  8     return multiply_list( xs) ** (1.0/len( xs))
 10   print geometric_mean( [1,2,4])
 11   print geometric_mean( [None,2,4])
Traceback (most recent call last):
  File "", line 11, in ?
    print geometric_mean( [None,2,4])
  File "", line 8, in geometric_mean
    return multiply_list( xs) ** (1.0/len( xs))
  File "", line 4, in multiply_list
    ret *= x
TypeError: unsupported operand type(s) for *=: 'int' and 'NoneType'
Doba běhu: 20.9 ms