Built-in Types for Interpreter Internals
A number of objects used by the internals of the interpreter are exposed to the user. These include traceback objects, code objects, frame objects, generator objects, slice objects, and the Ellipsis as shown in Table 3.10. It is relatively rare for programs to manipulate these objects directly, but they may be of practical use to tool-builders and framework designers.
Table 3.10 Built-in Python Types for Interpreter Internals
Type Name |
Description |
types.CodeType |
Byte-compiled code |
types.FrameType |
Execution frame |
types.GeneratorType |
Generator object |
types.TracebackType |
Stack traceback of an exception |
slice |
Generated by extended slices |
Ellipsis |
Used in extended slices |
Code Objects
Code objects represent raw byte-compiled executable code, or bytecode, and are typically returned by the built-in compile() function. Code objects are similar to functions except that they don’t contain any context related to the namespace in which the code was defined, nor do code objects store information about default argument values. A code object, c, has the following read-only attributes:
Attribute |
Description |
c.co_name |
Function name. |
c.co_argcount |
Number of positional arguments (including default values). |
c.co_nlocals |
Number of local variables used by the function. |
c.co_varnames |
Tuple containing names of local variables. |
c.co_cellvars |
Tuple containing names of variables referenced by nested functions. |
c.co_freevars |
Tuple containing names of free variables used by nested functions. |
c.co_code |
String representing raw bytecode. |
c.co_consts |
Tuple containing the literals used by the bytecode. |
c.co_names |
Tuple containing names used by the bytecode. |
c.co_filename |
Name of the file in which the code was compiled. |
c.co_firstlineno |
First line number of the function. |
c.co_lnotab |
String encoding bytecode offsets to line numbers. |
c.co_stacksize |
Required stack size (including local variables). |
c.co_flags |
Integer containing interpreter flags. Bit 2 is set if the function uses a variable number of positional arguments using "*args". Bit 3 is set if the function allows arbitrary keyword arguments using "**kwargs". All other bits are reserved. |
Frame Objects
Frame objects are used to represent execution frames and most frequently occur in traceback objects (described next). A frame object, f, has the following read-only attributes:
Attribute |
Description |
f.f_back |
Previous stack frame (toward the caller). |
f.f_code |
Code object being executed. |
f.f_locals |
Dictionary used for local variables. |
f.f_globals |
Dictionary used for global variables. |
f.f_builtins |
Dictionary used for built-in names. |
f.f_lineno |
Line number. |
f.f_lasti |
Current instruction. This is an index into the bytecode string of f_code. |
The following attributes can be modified (and are used by debuggers and other tools):
Attribute |
Description |
f.f_trace |
Function called at the start of each source code line |
f.f_exc_type |
Most recent exception type (Python 2 only) |
f.f_exc_value |
Most recent exception value (Python 2 only) |
f.f_exc_traceback |
Most recent exception traceback (Python 2 only) |
Traceback Objects
Traceback objects are created when an exception occurs and contain stack trace information. When an exception handler is entered, the stack trace can be retrieved using the sys.exc_info() function. The following read-only attributes are available in traceback objects:
Attribute |
Description |
t.tb_next |
Next level in the stack trace (toward the execution frame where the exception occurred) |
t.tb_frame |
Execution frame object of the current level |
t.tb_lineno |
Line number where the exception occurred |
t.tb_lasti |
Instruction being executed in the current level |
Generator Objects
Generator objects are created when a generator function is invoked (see Chapter 6, “Functions and Functional Programming”). A generator function is defined whenever a function makes use of the special yield keyword. The generator object serves as both an iterator and a container for information about the generator function itself. The following attributes and methods are available:
Attribute |
Description |
g.gi_code |
Code object for the generator function. |
g.gi_frame |
Execution frame of the generator function. |
g.gi_running |
Integer indicating whether or not the generator function is currently running. |
g.next() |
Execute the function until the next yield statement and return the value (this method is called __next__ in Python 3). |
g.send(value) |
Sends a value to a generator. The passed value is returned by the yield expression in the generator that executes until the next yield expression is encountered. send() returns the value passed to yield in this expression. |
g.close() |
Closes a generator by raising a GeneratorExit exception in the generator function. This method executes automatically when a generator object is garbage-collected. |
g.throw(exc [,exc_value [,exc_tb ]]) |
Raises an exception in a generator at the point of the current yield statement. exc is the exception type, exc_value is the exception value, and exc_tb is an optional traceback. If the resulting exception is caught and handled, returns the value passed to the next yield statement. |
Slice Objects
Slice objects are used to represent slices given in extended slice syntax, such as a[i:j:stride], a[i:j, n:m], or a[..., i:j]. Slice objects are also created using the built-in slice([i,] j [,stride]) function. The following read-only attributes are available:
Attribute |
Description |
s.start |
Lower bound of the slice; None if omitted |
s.stop |
Upper bound of the slice; None if omitted |
s.step |
Stride of the slice; None if omitted |
Slice objects also provide a single method, s.indices(length). This function takes a length and returns a tuple (start,stop,stride) that indicates how the slice would be applied to a sequence of that length. Here’s an example:
s = slice(10,20) # Slice object represents [10:20] s.indices(100) # Returns (10,20,1) --> [10:20] s.indices(15) # Returns (10,15,1) --> [10:15]
Ellipsis Object
The Ellipsis object is used to indicate the presence of an ellipsis (...) in an index lookup []. There is a single object of this type, accessed through the built-in name Ellipsis. It has no attributes and evaluates as True. None of Python’s built-in types make use of Ellipsis, but it may be useful if you are trying to build advanced functionality into the indexing operator [] on your own objects. The following code shows how an Ellipsis gets created and passed into the indexing operator:
class Example(object): def _ _getitem_ _(self,index): print(index) e = Example() e[3, ..., 4] # Calls e._ _getitem_ _((3, Ellipsis, 4))