Linux/Unix > Python Essential Reference, Second Edition > 3. Types and Objects > Built-in Types | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104028131052206173015093

### Built-in Types

Approximately two dozen types are built into the Python interpreter and grouped into a few major categories, as shown in Table 3.1. Some categories include familiar objects such as numbers and sequences. Others are used during program execution and are of little practical use to most programmers. The next few sections describe the most commonly used built-in types.

##### Table 3.1. Built-in Python Types

Type Category | Type Name | Description
--- | --- | ---
None | `NoneType` | The null object
Numbers | `IntType` `LongType` `FloatType` `ComplexType` | Integer Arbitrary-precision integer Floating-point number Complex number
Sequences | `StringType` `UnicodeType` `ListType` `TupleType` `XRangeType`

`BufferType`

Character string

Unicode character string

List

Tuple

Returned by `xrange()`

Buffer; returned by `buffer()`

Mapping | `DictType` | Dictionary
Callable | `BuiltinFunctionType` `BuiltinMethodType` `ClassType` `FunctionType` `InstanceType`

`MethodType`

`UnboundMethodType`

Built-in functions

Built-in methods

Class object

User-defined function

Class object instance

Bound class method

Unbound class method

Modules | `ModuleType` | Module
Classes | `ClassType` | Class definition
Class Instance | `InstanceType` | Class instance
Files | `FileType` | File
Internal | `CodeType` `FrameType` `TracebackType` `SliceType` `EllipsisType` | Byte-compiled code Execution frame Stack traceback of an exception Generated by extended slices Used in extended slices
Note: `ClassType` and `InstanceType` appear twice in Table 3.1 because classes and instances are both callable under special circumstances.

Note: `ClassType` and `InstanceType` appear twice in Table 3.1 because classes and instances are both callable under special circumstances.

#### The `None` Type

The `None` type denotes a null object. Python provides exactly one null object, which is written as `None` in a program. This object is returned by functions that don’t explicitly return a value. `None` is frequently used as the default value of optional arguments, so that the function can detect whether the caller has actually passed a value for that argument. `None` has no attributes and evaluates to false in Boolean expressions.

#### Numeric Types

Python uses four numeric types: integers, long integers, floating-point numbers, and complex numbers. All numeric objects are signed and immutable.

Integers represent whole numbers in the range of –2147483648 to 2147483647 (the range may be larger on some machines). Internally, integers are stored as 2’s complement binary values, in 32 or more bits. If the result of an operation exceeds the allowed range of values, an `OverflowError` exception is raised. Long integers represent whole numbers of unlimited range (limited only by available memory).

Floating-point numbers are represented using the native double-precision (64-bit) representation of floating-point numbers on the machine. Normally this is IEEE 754, which provides approximately 17 digits of precision and an exponent in the range of –308 to 308. This is the same as the `double` type in C. Python doesn’t support 32-bit single-precision floating-point numbers. If space and precision are an issue in your program, consider using Numerical Python (http://numpy.sourceforge.net).

Complex numbers are represented as a pair of floating-point numbers. The real and imaginary parts of a complex number `z` are available in `z` `.real` and `z` `.imag`.

#### Sequence Types

Sequences represent ordered sets of objects indexed by non-negative integers and include strings, Unicode strings, lists, tuples, xrange objects, and buffer objects. Strings and buffers are sequences of characters, xrange objects are sequences of integers, and lists and tuples are sequences of arbitrary Python objects. Strings, Unicode strings, and tuples are immutable; lists allow insertion, deletion, and substitution of elements. Buffers are described later in this section.

Table 3.2 shows the operators and methods that you can apply to all sequence types. Element `i` of a sequence `s` is selected using the indexing operator `s` `[``i` `]`, and a subsequence is selected using the slicing operator `s` `[``i` `:``j` `]`. (These operations are described in Chapter 4.) The length of any sequence is returned using the built-in `len(``s` `)` function. You can find the minimum and maximum values of a sequence by using the built-in `min(``s` `)` and `max(``s` `)` functions. However, these functions only work for sequences in which the elements can be ordered (typically numbers and strings).

Table 3.3 shows the additional operators that can be applied to mutable sequences such as lists.

##### Table 3.2. Operations and Methods Applicable to All Sequences

Item | Description
--- | ---
`s` `[``i` `]` | Returns element `i` of a sequence
`s` `[``i` `:``j` `]` | Returns a slice
`len(``s` `)` | Number of elements in `s`
`min(``s` `)` | Minimum value in `s`
`max(``s` `)` | Maximum value in `s`

##### Table 3.3. Operations Applicable to Mutable Sequences

Item | Description
--- | ---
`s` `[``i` `] =` `v` | Item assignment
`s` `[``i` `:``j` `] =` `t` | Slice assignment
`del` `s` `[``i` `]` | Item deletion
`del` `s` `[``i` `:``j` `]` | Slice deletion

Additionally, lists support the methods shown in Table 3.4. The built-in function `list(``s` `)` converts any sequence type to a list. If `s` is already a list, this function constructs a new list that’s a shallow copy of `s` . The `s` `.append(``x` `)` method appends a new element `x` to the end of the list. The `s` `.index(``x` `)` method searches the list for the first occurrence of `x` . If no such element is found, a `ValueError` exception is raised. Similarly, the `s` `.remove(``x` `)` method removes the first occurrence of `x` from the list. The `s` `.extend(``t` `)` method extends list `s` by appending the elements in sequence `t` .The `s` `.sort()` method sorts the elements of a list and optionally accepts a comparison function. This function should take two arguments and return negative, zero, or positive, depending on whether the first argument is smaller, equal to, or larger than the second argument, respectively. The `s` `.reverse()` method reverses the order of the items in the list. Both the `sort()` and `reverse()` methods operate on the list elements in place and return `None`.

##### Table 3.4. List Methods

Method | Description
--- | ---
`list(``s` `)` | Converts sequence `s` to a list.
`s` `.append(``x` `)` | Appends a new element `x` to the end of `s` .
`s` `.extend(``t` `)` | Appends a new list `t` to the end of `s` .
`s` `.count(``x` `)` | Counts occurrences of `x` in `s` .
`s` `.index(``x` `)` | Returns the smallest `i` where `s[i] == x` .
`s` `.insert(``i,x` `)` | Inserts `x` at index `i` .
`s` `.pop([``i` `])` | Returns the element `i` and removes it from the list. If `i` is omitted, the last element is returned.
`s` `.remove(``x` `)` | Searches for `x` and removes it from `s` .
`s` `.reverse()` | Reverses items of `s` in place.
`s` `.sort([``cmpfunc` `])` | Sorts items of `s` in place. `cmpfunc` is a comparison function.

Python provides two string object types. Standard strings are sequences of bytes containing 8-bit data. They may contain binary data and embedded null bytes. Unicode strings are sequences of 16-bit characters encoded in a format known as UCS-2. This allows for 65,536 unique character values. Although the latest Unicode standard supports up to 1 million unique character values, these extra characters are not currently supported by Python. Instead, they must be encoded as a special two-character (4-byte) sequence known as a surrogate pair—the interpretation of which is up to the application. Python does not check data for Unicode compliance or the proper use of surrogates.

Both standard and Unicode strings support the methods shown in Table 3.5. Although these methods operate on string instances, none of these methods actually modifies the underlying string data. Thus, methods such as `s` `.capitalize()`, `s` `.center()`, and `s` `.expandtabs()` always return a new string as opposed to modifying the string `s` . Character tests such as `s` `.isalnum()` and `s` `.isupper()` return true or false if all the characters in the string `s` satisfy the test. Furthermore, these tests always return false if the length of the string is zero. The `s` `.find()`, `s` `.index()`, `s` `.rfind()`, and `s` `.rindex()` methods are used to search `s` for a substring. All these functions return an integer index to the substring in `s` . In addition, the `find()` method returns `-1` if the substring isn’t found, whereas the `index()` method raises a `ValueError` exception. Many of the string methods accept optional `start` and `end` parameters, which are integer values specifying the starting and ending indices in `s` . The `s` `.translate()` method is used to perform character substitutions, and is described in the `string` module in Appendix A. The `s` `.encode()` method is used to transform the string data into a specified character encoding. As input it accepts an encoding name such as `'ascii'`, `'utf-8'`, or `'utf-16'`. This method is most commonly used to convert Unicode strings into a data encoding suitable for I/O operations and is described further in Chapter 9, “Input and Output.” More details about string methods can be found in the documentation for the `string` module (see Appendix A).

##### Table 3.5. String Methods

Method | Description
--- | ---
`s` `.capitalize()` | Capitalizes the first character of `s` .
`s` `.center(``width` `)` | Centers the string in a field of length `width` .
`s` `.count(``sub` `[,``start` `[,``end` `]])` | Counts occurrences of the specified substring `sub` .
`s` `.encode([``encoding` `[,``errors` `]])` | Returns an encoded version of the string.
`s` `.endswith(``suffix` `[,``start` `[,``end` `]])` | Checks the end of the string for a suffix.
`s` `.expandtabs([``tabsize` `])` | Expands tabs.
`s` `.find(``sub` `[,``start` `[,``end` `]])` | Finds the first occurrence of the specified substring `sub` .
`s` `.index(``sub` `[,``start` `[,``end` `]])` | Finds the first occurrence of `sub` or raises an exception.
`s` `.isalnum()` | Checks whether all characters are alphanumeric.
`s` `.isalpha()` | Checks whether all characters are alphabetic.
`s` `.isdigit()` | Checks whether all characters are digits.
`s` `.islower()` | Checks whether all characters are lowercase.
`s` `.isspace()` | Checks whether all characters are whitespace.
`s` `.istitle()` | Checks whether the string is title-cased (first letter of each word capitalized).
`s` `.isupper()` | Checks whether all characters are uppercase.
`s` `.join(``t` `)` | Joins the strings in list `t` using `s` as a delimiter.
`s` `.ljust(``width` `)` | Left-aligns `s` in a string of size `width` .
`s` `.lower()` | Returns `s` converted to lowercase.
`s` `.lstrip()` | Removes leading whitespace.
`s` `.replace(``old` `,` `new` `[,``maxreplace` `])` | Replaces the substring `old` with `new` .
`s` `.rfind(``sub` `[,``start` `[,``end` `]])` | Finds the last occurrence of a substring.
`s` `.rindex(``sub` `[,``start` `[,``end` `]])` | Finds the last occurrence of `sub` or raises an exception.
`s` `.rjust(``width` `)` | Right-aligns `s` in a string of length `width` .
`s` `.rstrip()` | Removes trailing whitespace.
`s` `.split([``sep` `[,``maxsplit` `]])` | Splits a string using `sep` as a delimiter. `maxsplit` is the maximum number of splits to perform.
`s` `.splitlines([``keepends` `])` | Splits a string into a list of lines. If `keepends` is `1`, trailing newlines are preserved.
`s` `.startswith(``prefix` `[,``start` `[,``end` `]])` | Checks whether a string starts with `prefix` .
`s` `.strip()` | Removes leading and trailing whitespace.
`s` `.swapcase()` | Returns `s` with uppercase converted to lowercase and vice versa.
`s` `.title()` | Returns a title-cased version of the string.
`s` `.translate(``table` `[,``deletechars` `])` | Translates a string using a character translation table.
`s` `.upper()` | Returns `s` converted to uppercase.

The built-in function `range([``i` `,]``j` `[,``stride` `])` constructs a list and populates it with integers `k` such that `i <` `=` `k` `<` `j` . The first index `i` and the `stride` are optional and have default values of `0` and `1`, respectively. The built-in function `xrange([``i` `,]``j` `[,``stride` `])` performs a similar operation, but returns an immutable sequence of type `XRangeType`. Rather than storing all the values in a list, this sequence calculates its values whenever it’s accessed. Consequently, it’s much more memory efficient when working with large sequences of integers. The `XRangeType` provides a single method, `s` `.tolist()`, that converts its values to a list.

Buffer objects are typically used to provide a sequence interface to a region of memory in which each byte is treated as an 8-bit character.Although there is no special syntax for creating a buffer object, they can be created using the built-in function `buffer(``obj` `[,` `offset` `[,` `size` `]])`. Buffer objects usually share the same memory as that of the underlying object `obj` . Because of this, they can sometimes be used as a more memory-efficient mechanism for taking slices of strings and other byte-oriented data. In addition, buffers can sometimes be used to access the raw data used to store the contents of other Python types such as arrays in the array module and Unicode strings. Buffers may or may not be mutable, depending on the mutability of `obj` .

#### Mapping Types

A mapping object represents an arbitrary collection of objects that are indexed by another collection of nearly arbitrary key values. Unlike a sequence, a mapping object is unordered and can be indexed by numbers, strings, and other objects. Mappings are mutable.

Dictionaries are the only built-in mapping type and are Python’s version of a hash table or associative array. You can use any immutable object as a dictionary key value (strings, numbers, tuples, and so on). Lists, dictionaries, or tuples containing mutable objects cannot be used as keys. (The dictionary type requires key values to remain constant.)

To select an item in a mapping object, use the key index operator `m` `[``k` `]` where `k` is a key value. If the key is not found, a `KeyError` exception is raised. The `len(``m` `)` function returns the number of items contained in a mapping object. Table 3.6 lists methods and operations.

##### Table 3.6. Methods and Operations for Mapping Types

Item | Description
--- | ---
`len(``m` `)` | Returns the number of items in `m` .
`m` `[``k` `]` | Returns the item of `m` with key `k` .
`m` `[``k` `] =` `x` | Sets `m` `[``k` `]` to `x` .
`del` `m` `[``k` `]` | Removes `m` `[``k` `]` from `m` .
`m` `.clear()` | Removes all items from `m` .
`m` `.copy()` | Returns a copy of `m` .
`m` `.has_key(``k` `)` | Returns `1` if `m` has key `k` , `0` otherwise.
`m` `.items()` | Returns a list of `(``key` `,``value` `)` pairs.
`m` `.keys()` | Returns a list of key values.
`m` `.update(``b` `)` | Adds all objects from dictionary `b` to `m` .
`m` `.values()` | Returns a list of all values in `m` .
`m` `.get(``k` `[,``v` `])` | Returns `m` `[``k` `]` if found; otherwise, returns `v` .
`m` `.setdefault(``k` `[,` `v` `])` | Returns `m` `[``k` `]` if found; otherwise, returns `v` and sets `m` `[``k` `] =` `v` .
`m` `.popitem()` | Removes a random `(``key` `,``value` `)` pair from `m` and returns it as a tuple.

The `m` `.clear()` method removes all items. The `m` `.copy()` method makes a shallow copy of the items contained in a mapping object and places them in a new mapping object. The `m` `.items()` method returns a list containing (key,value) pairs. The `m` `.keys()` method returns a list with all the key values and the `m` `.values()` method returns a list with all the objects. The `m` `.update(``b` `)` method updates the current mapping object by inserting all the (key,value) pairs found in the mapping object `b` . The `m` `.get(``k` `[,``v` `])` method retrieves an object, but allows for an optional default value `v` that’s returned if no such object exists. The `m` `.setdefault(``k` `[,``v` `])` method is similar to `m` `.get()` except that in addition to returning `v` if no object exists, it sets `m` `[``k` `] =` `v` . If `v` is omitted, it defaults to `None`. The `m` `.popitem()` method is used to iteratively destroy the contents of a dictionary.

#### Callable Types

Callable types represent objects that support the function call operation. There are several flavors of objects with this property, including user-defined functions, built-in functions, and methods associated with classes.

User-defined functions are callable objects created at the module level by using the `def` statement or `lambda` operator. (Functions defined within class definitions are called methods and are described shortly.) Functions are first-class objects that behave just like any other Python object. As a result, you can assign them to variables or place them in lists, tuples, and dictionaries, as shown in the following example:

    def foo(x,y):
        print '%s + %s is %s' % (str(x), str(y), str(x+y))

    # Assign to a new variable
    bar = foo
    bar(3,4)            # Invokes 'foo' defined above

    # Place in a container
    d = { }
    d['callback'] = foo
    d['callback'](3,4)  # Invokes 'foo'

A user-defined function `f` has the following attributes:

Attribute(s) | Description
--- | ---
`f` `._ _doc_ _ or` `f` `.func_doc` | Documentation string
`f` `._ _name_ _ or` `f` `.func_name` | Function name
`f` `._ _dict_ _ or` `f` `.func_dict` | Dictionary containing function attributes
`f` `.func_code` | Byte-compiled code
`f` `.func_defaults` | Tuple containing the default arguments
`f` `.func_globals` | Dictionary defining the global namespace
`f` `.func_closure` | Tuple containing data related to nested scopes

Methods are functions that operate only on instances of an object. Typically, methods are defined inside a class definition, as shown in Listing 3.1.

##### Listing 3.1 Defining a Method

    # A queue of objects ranked by priorities
    class PriorityQueue:
        def _ _init_ _(self):
              self.items = [ ]           # List of (priority, item)
        def insert(self,priority,item):
              for i in range(len(self.items)):
                    if self.items[i][0] > priority:
                            self.items.insert(i,(priority,item))
                            break
              else:
                    self.items.append((priority,item))
        def remove(self):
              try:
                    return self.items.pop(0)[1]
              except IndexError:
                    raise RuntimeError, 'Queue is empty'

An unbound method object is a method that hasn’t yet been associated with a specific instance of an object. The methods contained within a class definition are unbound until they’re attached to a specific object. For example:

    m = PriorityQueue.insert         # Unbound method

To invoke an unbound method, supply an instance of an object as the first argument:

    pq = PriorityQueue()
    m = PriorityQueue.insert
    m(pq,5,"Python")                    # Invokes pq.insert(5,"Python")

A bound method object is a function that has been bound to a specific object instance. For example:

    pq = PriorityQueue()      # Create a PriorityQueue instance
    n = pq.insert             # n is a method bound to pq

A bound method implicitly contains a reference to the associated instance, so it can be invoked as follows:

    n(5,"Python")                      # Invokes pq.insert(5,"Python")

Bound and unbound methods are no more than a thin wrapper around an ordinary function object. The following attributes are defined for method objects:

Attribute | Description
--- | ---
`m` `._ _doc_ _` | Documentation string
`m` `._ _name_ _` | Method name
`m` `._ _dict_ _` | Method attributes
`m` `.im_class` | Class in which this method was defined
`m` `.im_func` | Function object implementing the method
`m` `.im_self` | Instance associated with the method (`None` if unbound)

So far, this discussion has focused on functions and methods, but class objects (described shortly) are also callable. When a class is called, a new class instance is created. In addition, if the class defines an `_ _init_ _()` method, it’s called to initialize the newly created instance. The creation of a `PriorityQueue` in the earlier example illustrates this behavior.

A class instance is also callable if its class defines a special method `_ _call_ _()`. If this method is defined for a class instance `x` , then `x` `(``args` `)` invokes the method

    x._ _call_ _ (args).

The final types of callable objects are built-in functions and methods. Built-in functions and methods correspond to code written in extension modules and are usually written in C or C++. The following attributes are available for built-in methods:

Attribute | Description
--- | ---
`b` `._ _doc_ _` | Documentation string
`b` `._ _name_ _` | Function/method name
`b` `._ _self_ _` | Instance associated with the method
`b` `._ _members_ _` | List of method attribute names

For built-in functions such as `len()`, the `_ _self_ _` is set to `None`, indicating that the function isn’t bound to any specific object. For built-in methods such as `x` `.append()` where `x` is a list object, `_ _self_ _` is set to `x` .

#### Modules

The module type is a container that holds objects loaded with the `import` statement. When the statement `import foo` appears in a program, for example, the name `foo` is assigned to the corresponding module object. Modules define a namespace that’s implemented using a dictionary accessible in the attribute `_ _dict_ _`. Whenever an attribute of a module is referenced (using the dot operator), it’s translated into a dictionary lookup. For example, `m` `.``x` is equivalent to `m` `._ _dict_ _["``x` `"]`. Likewise, assignment to an attribute such as `m` `.``x` `=` `y` is equivalent to `m` `._ _dict_ _["x"] =` `y` . The following attributes are available:

Attribute | Description
--- | ---
`m` `._ _dict_ _` | Dictionary associated with the module
`m` `._ _doc_ _` | Module documentation string
`m` `._ _name_ _` | Name of the module
`m` `._ _file_ _` | File from which the module was loaded
`m` `._ _path_ _` | Fully qualified package name, defined when the module object refers to a package

#### Classes

Classes are created using the `class` statement, as described in Chapter 7. Like modules, classes are implemented using a dictionary that contains all the objects defined within the class, and defines a namespace. References to class attributes such as `c` `.``x` are translated into a dictionary lookup `c` `._ _dict_ _["``x` `"]`. If an attribute isn’t found in this dictionary, the search continues in the list of base classes. This search is depth first, left to right, in the order that base classes were specified in the class definition. Attribute assignment such as `c` `.``y` `= 5` always updates the `_ _dict_ _` attribute of `c` , not the dictionaries of any base class.

The following attributes are defined by class objects:

Attribute | Description
--- | ---
`c` `._ _dict_ _` | Dictionary associated with the class
`c` `._ _doc_ _` | Class documentation string
`c` `._ _name_ _` | Name of the class
`c` `._ _module_ _` | Name of the module in which the class was defined
`c` `._ _bases_ _` | Tuple containing base classes

#### Class Instances

A class instance is an object created by calling a class object. Each instance has its own local namespace that’s implemented as a dictionary. This dictionary and the associated class object have the following attributes:

Attribute | Description
--- | ---
`x` `._ _dict_ _` | Dictionary associated with an instance
`x` `._ _class_ _` | Class to which an instance belongs

When the attribute of an object is referenced, such as in `x` `.``a` , the interpreter first searches in the local dictionary for `x` `._ _dict_ _["``a` `"]`. If it doesn’t find the name locally, the search continues by performing a lookup on the class defined in the `_ _class_ _` attribute. If no match is found, the search continues with base classes as described earlier. If still no match is found and the object’s class defines a `_ _getattr_ _()` method, it’s used to perform the lookup. The assignment of attributes such as `x` `.``a` `= 4` always updates `x` `._ _dict_ _`, not the dictionaries of classes or base classes.

#### Files

The file object represents an open file and is returned by the built-in `open()` function (as well as a number of functions in the standard library). For more details about this type, see Chapter 9.

#### Internal Types

A number of objects used by the interpreter are exposed to the user. These include traceback objects, code objects, frame objects, slice objects, and the Ellipsis object.

##### 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 read-only attributes described in the following table:

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_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` | Filename 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_restricted` | Set to `1` if executing in restricted execution mode.
`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
`f` `.f_exc_value` | Most recent exception value
`f` `.f_exc_traceback` | Most recent exception traceback

##### Traceback Objects

Traceback objects are created when an exception occurs and contains 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

##### 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

##### Ellipsis Object

The Ellipsis object is used to indicate the presence of an ellipsis (`…`) in a slice. There is a single object of this type, accessed through the built-in name `Ellipsis`. It has no attributes and evaluates as true.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.