# 9.2 How It Works

Some changes were made to the interpreter:

- sys.settrace(func) sets the global trace function
- there can also a local trace function (see later)

Trace functions have three arguments: (frame, event, arg)

frame
  is the current stack frame

event
  is a string: `'call'`, `'line'`, `'return'` or `'exception'`

arg
  is dependent on the event type

The global trace function is invoked (with event set to `'call'`) whenever a new local scope is entered; it should return a reference to the local trace function to be used that scope, or `None` if the scope shouldn't be traced.

The local trace function should return a reference to itself (or to another function for further tracing in that scope), or `None` to turn off tracing in that scope.

Instance methods are accepted (and very useful!) as trace functions.

The events have the following meaning:

`'call'`
  A function is called (or some other code block entered). The global trace function is called; arg is the argument list to the function; the return value specifies the local trace function.

`'line'`
  The interpreter is about to execute a new line of code (sometimes multiple line events on one line exist). The local trace function is called; arg in None; the return value specifies the new local trace function.

`'return'`
  A function (or other code block) is about to return. The local trace function is called; arg is the value that will be returned. The trace function's return value is ignored.

`'exception'`
  An exception has occurred. The local trace function is called; arg is a triple (exception, value, traceback); the return value specifies the new local trace function

Note that as an exception is propagated down the chain of callers, an `'exception'` event is generated at each level.

Stack frame objects have the following read-only attributes:

f_code
  the code object being executed
f_lineno
  the current line number (`-1` for `'call'` events)
f_back
  the stack frame of the caller, or None
f_locals
  dictionary containing local name bindings
f_globals
  dictionary containing global name bindings

Code objects have the following read-only attributes:

co_code
  the code string
co_names
  the list of names used by the code
co_consts
  the list of (literal) constants used by the code
co_filename
  the filename from which the code was compiled