Linux/Unix > Python Essential Reference, Second Edition > A. The Python Library > Built-in Functions and Exceptions | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105082191052001041189214

### Built-in Functions and Exceptions

This section describes Python’s built-in functions and exceptions. Much of this material is covered less formally in the chapters of this book. Additional details and some of the more subtle aspects of many built-in functions can be found here.

#### Built-in Functions

The functions in this section are always available to the interpreter and are contained within the `_ _builtin_ _` module. In addition, the `_ _builtins_ _` attribute of each module usually refers to this module (except when running in a restricted execution environment as described in the “Restricted Execution” section).

`_` (Underscore)

By default, the `_` variable is set to the result of the last expression evaluated when the interpreter is running in interactive mode.

? See Also `sys.displayhook` (118).

    _ _import_ _(name [, globals [, locals [, fromlist]]])

This function is invoked by the `import` statement to load a module. `name` is a string containing the module name, `globals` is an optional dictionary defining the global namespace, `locals` is a dictionary defining the local namespace, and `fromlist` is a list of targets given to the `from` statement. For example, the statement `import spam` results in a call to `_ _import_ _('spam', globals(), locals(), [])`, while the statement `from spam import foo` results in a call `_ _import_ _ ('spam', globals(), locals(), ['foo'])`. If the module name is prefixed by a package name such as `foo.bar` and `fromlist` is empty, the corresponding module object is returned. If `fromlist` is not empty, only the top-level package is returned.

This function is intended to be a low-level interface to the module loader. It doesn’t perform all the steps performed by an `import` statement (in particular, the local namespace is not updated with names referring to objects contained within the module). This function can be redefined by the user to implement new behaviors for `import`. The default implementation doesn’t even look at the `locals` parameter, while `globals` is only used to determine package context (these parameters are supplied so that alternative implementations of `_ _import_ _()` have full access to the global and local namespace information where `import` statements appear).

    abs(x)

Returns the absolute value of `x` .

    apply(func [, args [, keywords]])

Performs a function call operation on a callable object `func. args` is a tuple containing positional arguments and `keywords` is a dictionary containing keyword arguments. The `apply()` function can also be written as `func` `(*``args` `,**``keywords` `)`.

    buffer(sequence [, offset [, size]])

Creates a new buffer object. A buffer is typically a byte-oriented subsequence of another sequence such as a string. For the most part, buffers appear like strings except that they don’t support string methods and can’t be used with the functions in the `string` module.

    callable(object)

Returns `1` if `object` is a callable object, `0` otherwise.

    chr(i)

Converts an integer or long integer value `i` , `0 <= i <= 255`, into a one-character string.

    cmp(x, y)

Compares `x` and `y` and returns a negative number if `x` `<` `y` , `0` if `x` `==` `y` , and a positive number if `x` `>` `y` . Any two objects can be compared, although the result may be meaningless if the two objects have no meaningful comparison method defined (for example, comparing a number with a file object). In certain circumstances, such comparisons may also raise an exception.

    coerce(x, y)

Returns a tuple containing the values of `x` and `y` converted to a common numerical type. See the section “Mathematical Operations” in Chapter 3, “Types and Objects.”

    compile(string, filename, kind)

Compiles `string` into a code object for use with `exec` or `eval()`. `filename` is a string containing the name of the file in which the string was defined. `kind` is `'exec'` for a sequence of statements, `'eval'` for a single expression, or `'single'` for a single executable statement.

    complex(real [, imag])

Creates a complex number.

    delattr(object, attr)

Deletes an attribute of an object. `attr` is a string. Same as `del` `object` `.``attr` .

    dir([object])

Returns a sorted list of attribute names. These are taken from the object’s `_ _dict_ _`, `_ _methods_ _`, and `_ _members_ _` attributes. If no argument is given, the names in the current local symbol table are returned.

    divmod(a, b)

Returns the quotient and remainder of long division as a tuple. For integers, the value `(``a` `/` `b` `,` `a` `%` `b` `)` is returned. For floats, `(math.floor(``a` `/` `b` `),` `a` `%` `b` `)` is returned.

    eval(expr [, globals [, locals]])

Evaluates an expression. `expr` is a string or a code object created by `compile()`. `globals` and `locals` define the global and local namespaces for the operation. If omitted, the expression is evaluated in the namespace of the caller.

    execfile(filename [, globals [, locals]])

Executes the statements in the file `filename` . `globals` and `locals` define the global and local namespaces in which the file is executed. If omitted, the file’s contents are executed in the namespace of the caller. This function should not be used inside a function body because it is incompatible with nested scopes.

    filter(function, list)

Creates a new list consisting of the objects from `list` for which `function` evaluates to true. If `function` is `None`, the identity function is used and all the elements of `list` that are false are removed.

    float(x)

Converts `x` to a floating-point number.

    getattr(object, name [, default])

Returns an attribute of an object. `name` is a string. `default` is an optional value to return if no such attribute exists. Same as `object` `.``name` .

    globals()

Returns a dictionary corresponding to the global namespace of the caller.

    hasattr(object, name)

Returns `1` if `name` is the name of an attribute of `object` , `0` otherwise. `name` is a string.

    hash(object)

Returns an integer hash value for an object (if possible). The hash value is the same for any two objects that compare as equals. Mutable objects don’t define a hash value.

    hex(x)

Converts an integer or long integer `x` to a hexadecimal string.

    id(object)

Returns the unique integer identity of `object` .

    input([prompt])

Same as `eval(raw_input(``prompt` `))`.

    int(x [, base])

Converts a number or string `x` to an integer. `base` optionally specifies a base when converting from a string.

    intern(string)

Checks to see whether `string` is contained in an internal table of strings. If found, a copy of the internal string is returned. If not, `string` is added to the internal table and returned. This function is primarily used to get better performance in operations involving dictionary lookups. Interned strings are never garbage-collected. Not applicable to Unicode strings.

    isinstance(object, classobj)

Returns true if `object` is an instance of `classobj` or a subclass of `classobj` . Can also be used for type checking if `classobj` is a type object.

    issubclass(class1, class2)

Returns true if `class1` is a subclass of (derived from) `class2` .

Note: `issubclass(``A` `,` `A` `)` is true.

    len(s)

Returns the number of items contained in the sequence `s` .

    list(s)

Returns a new list consisting of the items in the sequence `s` .

    locals()

Returns a dictionary corresponding to the local namespace of the caller.

    long(x [, base])

Converts a number or string `x` to a long integer. `base` optionally specifies the base of the conversion when converting from a string.

    map(function, list, ...)

Applies `function` to every item of `list` and returns a list of results. If multiple lists are supplied, `function` is assumed to take that many arguments, with each argument taken from a different list. If `function` is `None`, the identity function is assumed. If `None` is mapped to multiple lists, a list of tuples is returned, wherein each tuple contains an element from each list. Short lists are extended with values of `None` to match the length of the longest list, if necessary. Consider using list comprehensions instead of `map`. For example, `map(``function` `,` `alist` `)` can be replaced by `[``function` `(x) for x in` `alist` `]`.

? See Also `zip` (105).

    max(s [, args, ...])

For a single argument `s` , returns the maximum value of the sequence `s` . For multiple arguments, returns the largest of the arguments.

    min(s [, args, ...])

For a single argument `s` , returns the minimum value of the sequence `s` . For multiple arguments, returns the smallest of the arguments.

    oct(x)

Converts an integer or long integer `x` to an octal string.

    open(filename [, mode [, bufsize]])

Opens the file `filename` and returns a new file object (see Chapter 10, “Execution Environment”). `mode` indicates how the file should be opened: `'r'` for reading, `'w'` for writing, and `'a'` for appending. An optional `'+'` can be added to the mode to open the file for updating (which allows both reading and writing). A mode of `'w+'` truncates the file to zero length if it already exists. A mode of `'r+'` or `'a+'` opens the file for both reading and writing, but leaves the original contents intact when the file is opened. Append `'b'` to the mode to indicate binary mode on platforms such as Windows, where a distinction is made between text and binary files. If the mode is omitted, a mode of `'r'` is assumed. The `bufsize` argument specifies the buffering behavior, where `0` is unbuffered, `1` is line buffered, and any other positive number indicates an approximate buffer size in bytes. A negative number indicates that the system default buffering should be used (this is the default behavior).

    ord(c)

Returns the integer ordinal value of a single character `c` . For ordinary characters, a value in the range `[0,255]` is returned. For Unicode characters, a value in the range `[0,65535]` is returned.

    pow(x, y [, z])

Returns `x` `**` `y` . If `z` is supplied, returns `(``x` `**` `y` `) %` `z` .

    range([start,] stop [, step])

Creates a list of integers from `start` to `stop` . `step` indicates a stride and is set to `1` if omitted. If `start` is omitted (when `range()` is called with one argument), it defaults to `0`. A negative `step` creates a list of numbers in descending order.

? See Also `xrange` (105).

    raw_input([prompt])

Reads a line of input from standard input (`sys.stdin`) and returns it as a string. If `prompt` is supplied, it’s first printed to standard output (`sys.stdout`). Trailing newlines are stripped and an `EOFError` exception is raised if an EOF is read. If the `readline` module is loaded, this function will use it to provide advanced line-editing and command-completion features.

    reduce(func, seq [, initializer])

Applies a function `func` cumulatively to the items in the sequence `seq` and returns a single value. `func` is expected to take two arguments and is first applied to the first two items of `seq` . This result and subsequent elements of `seq` are then combined one at a time in a similar manner, until all elements of `seq` have been consumed. `initializer` is an optional starting value used in the first computation and when `seq` is empty.

    reload(module)

Reloads an already imported module. `module` must refer to an existing module object. The use of this function is discouraged except for debugging. Keep the following issues in mind:

- When a module is reloaded, the dictionary defining its global namespace is retained. Thus, definitions in the old module that aren’t part of the newly reloaded module are retained. Modules can exploit this to see if they have been previously loaded.

- It’s usually illegal to reload dynamically loaded modules written in C.

- If any other modules have imported this module by using the `from` statement, they’ll continue to use the definitions in the previously imported module. This problem can be avoided by either reissuing the `from` statement after a module has been reloaded or using fully qualified names such as `module` `.``name` .

- If there are any object instances created by classes in the old module, they’ll continue to use methods defined in the old module.

    repr(object)

Returns a string representation of `object` . This is the same string generated by backquotes (``object``). In most cases, the returned string is an expression that can be passed to `eval()` to re-create the object.

    round(x [, n])

Returns the result of rounding the floating-point number `x` to the closest multiple of 10 to the power minus `n` . If `n` is omitted, it defaults to `0`. If two multiples are equally close, rounding is done away from `0` (for example, `0.5` is rounded to `1.0` and `-0.5` is rounded to `-1.0`).

    setattr(object, name, value)

Sets an attribute of an object. `name` is a string. Same as `object` `.``name` `=` `value` .

    slice([start,] stop [, step])

Returns a slice object representing integers in the specified range. Slice objects are also generated by extended slice syntax. See the section “Sequence and Mapping Methods” in Chapter 3 for details.

    str(object)

Returns a string representing the printable form of an object. This is the same string as would be produced by the `print` statement.

    tuple(s)

Creates a tuple whose items are taken from the sequence `s` . If `s` is already a tuple, it’s returned unmodified.

    type(object)

Returns the type of `object`. The type is returned as a type object as defined in the `types` module.

? See Also `isinstance` (102).

    unichr(i)

Converts the integer or long integer `i` , `0 <=` `i` `<= 65535`, to a single Unicode character.

    unicode(string [, encoding [, errors]])

Converts `string` to a Unicode string. `encoding` specifies the data encoding of `string` . If omitted, the default encoding as returned by `sys.getdefaultencoding()` is used. `errors` specifies how encoding errors are handled and is one of `'strict'`, `'ignore'`, or `'replace'`. See Chapter 9 (“Input and Output”) and Chapter 3 (“Types and Objects”) for details.

    vars([object])

Returns the symbol table of `object` (usually found in its `_ _dict_ _` attribute). If no argument is given, a dictionary corresponding to the local namespace is returned.

    xrange([start,] stop [, step])

Works like `range()` except that an `XRangeType` object is returned. This object produces the same values as stored in the list created by `range()`, but without actually storing them. This is useful when working with very large ranges of integers that would consume a large amount of memory.

    zip(s1 [, s2 [,..]])

Returns a list of tuples where the nth tuple is `(``s1` `[``n` `],` `s2` `[``n` `], ...)`. The resulting list is truncated to the length of the shortest argument sequence.

#### Built-in Exceptions

Built-in exceptions are contained in the `exceptions` module, which is always loaded prior to the execution of any program. Exceptions are defined as classes. The following exceptions serve as base classes for all the other exceptions:

    Exception

The root class for all exceptions. All built-in exceptions are derived from this class. User-defined exceptions are encouraged to use this as a base class.

    StandardError

The base class for all built-in exceptions except for `SystemExit`.

    ArithmeticError

Base class for arithmetic exceptions, including `OverflowError`, `ZeroDivisionError`, and `FloatingPointError`.

    LookupError

Base class for indexing and key errors, including `IndexError` and `KeyError`.

    EnvironmentError

Base class for errors that occur outside Python, including `IOError` and `OSError`.

The preceding exceptions are never raised explicitly. However, they can be used to catch certain classes of errors. For instance, the following code would catch any sort of numerical error:

    try:
        # Some operation
        ...
    except ArithmeticError, e:
        # Math error

When an exception is raised, an instance of an exception class is created. This instance is placed in the optional variable supplied to the `except` statement. For example:

    except IOError, e:
        # Handle error
        # 'e' has an instance of IOError

Most exceptions have an associated value that can be found in the `args` attribute of the exception instance (`'e.args'` in the preceding example). In most cases, this is a string describing the error. For `EnvironmentError` exceptions, the value is a 2-tuple or 3-tuple containing an integer error number, string error message, and an optional filename (these values are also available as exception attributes as described below).

The following exceptions are raised by programs:

    AssertionError

Failed `assert` statement.

    AttributeError

Failed attribute reference or assignment.

    EOFError

End of file. Generated by the built-in functions `input()` and `raw_input()`. Note: A number of I/O methods such as `read()` and `readlines()` return an empty string for EOF.

    FloatingPointError

Failed floating-point operation. A subclass of `ArithmeticError`.

    IOError

Failed I/O operation. The value is an `IOError` instance with attributes `errno`, `strerror`, and `filename`. `errno` is an integer error number, `strerror` is a string error message, and `filename` is an optional filename. A subclass of `EnvironmentError`.

    ImportError

Raised when an `import` statement can’t find a module or when `from` can’t find a name in a module.

    IndentationError

Indentation error. A subclass of `SyntaxError`.

    IndexError

Sequence subscript out of range. A subclass of `LookupError`.

    KeyError

Key not found in a dictionary. A subclass of `LookupError`.

    KeyboardInterrupt

Raised when the user hits the interrupt key (usually Ctrl+C).

    MemoryError

Recoverable out-of-memory error.

    NameError

Name not found in local or global namespaces.

    NotImplementedError

Unimplemented feature. Can be raised by base classes that require derived classes to implement certain methods. A subclass of `RuntimeError`.

    OSError

Operating system error. Primarily raised by functions in the `os` module. The value is the same as for `IOError`. A subclass of `EnvironmentError`.

    OverflowError

Result of arithmetic operation is too large to be represented. A subclass of `ArithmeticError`.

    RuntimeError

A generic error not covered by any of the other categories.

    SyntaxError

Parser syntax error. Instances have the attributes `filename`, `lineno`, `offset`, and `text` that can be used to gather more information.

    SystemError

Internal error in the interpreter. The value is a string indicating the problem.

    SystemExit

Raised by the `sys.exit()` function. The value is an integer indicating the return code. If it’s necessary to exit immediately, `os._exit()` can be used.

    TabError

Inconsistent tab usage. Generated when Python is run with the `-tt` option. A subclass of `SyntaxError`.

    TypeError

Operation or function applied to an object of inappropriate type.

    UnboundLocalError

Unbound local variable referenced. This error occurs if a variable is referenced before it’s defined in a function. A subclass of `NameError`.

    UnicodeError

Unicode encoding or decoding error. A subclass of `ValueError`.

    ValueError

Generated when the argument to a function or operation is the right type, but of inappropriate value.

    WindowsError

Generated by failed system calls on Windows. A subclass of `OSError`.

    ZeroDivisionError

Dividing by zero. A subclass of `ArithmeticError`.

The `exceptions` module also defines the exception objects `Warning`, `UserWarning`, `DeprecationWarning`, `RuntimeWarning`, and `SyntaxWarning`. These exceptions are used as part of the Python warning framework and are described further in the `warnings` module.

? See Also warnings (121).

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