12. Built-In Functions and Exceptions

This chapter describes Python’s built-in functions and exceptions. Much of this material is covered less formally in earlier chapters of this book. This chapter merely consolidates all this information into one section and expands upon some of the more subtle features of certain functions. Also, Python 2 includes a number of built-in functions that are considered to be obsolete and which have been removed from Python 3. Those functions are not documented here—instead the focus is on modern functionality.

Built-in Functions and Types

Certain types, functions, and variables are always available to the interpreter and can be used in any source module. Although you don’t need to perform any extra imports to access these functions, they are contained in a module _ _builtin_ _ in Python 2 and in a module builtins in Python 3. Within other modules that you import, the variable _ _builtins_ _ is also bound to this module.

abs(x)

Returns the absolute value of x.

all(s)

Returns True if all of the values in the iterable s evaluate as True.

any(s)

Returns True if any of the values in the iterable s evaluate as True.

ascii(x)

Creates a printable representation of the object x just like the repr(), but only uses ASCII characters in the result. Non-ASCII characters are turned into appropriate escape sequences. This can be used to view Unicode strings in a terminal or shell that doesn’t support Unicode. Python 3 only.

basestring

This is an abstract data type that is the superclass of all strings in Python 2 (str and unicode). It is only used for type testing of strings. For example, isinstance(s,basestring) returns True if s is either kind of string. Python 2 only.

bin(x)

Returns a string containing the binary representation of the integer x.

bool([x])

Type representing Boolean values True and False. If used to convert x, it returns True if x evaluates to true using the usual truth-testing semantics (that is, nonzero number, non-empty list, and so on). Otherwise, False is returned. False is also the default value returned if bool() is called without any arguments. The bool class inherits from int so the Boolean values True and False can be used as integers with values 1 and 0 in mathematical calculations.

bytearray([x])

A type representing a mutable array of bytes. When creating an instance, x may be an iterable sequence of integers in the range 0 to 255, an 8-bit string or bytes literal, or an integer that specifies the size of the byte array (in which case every entry will be initialized to 0). A bytearray object a looks like an array of integers. If you perform a lookup such as a[i], you will get an integer value representing the byte value at index i. Assignments such as a[i] = v also require v to be an integer byte value. However, a bytearray also provides all of the operations normally associated with strings (that is, slicing, find(), split(), replace(), and so on). When using these string operations, you should be careful to preface all string literals with b in order to indicate that you’re working with bytes. For example, if you wanted to split a byte array a into fields using a comma character separator, you would use a.split(b',') not a.split(','). The result of these operations is always new bytearray objects, not strings. To turn a bytearray a into a string, use the a.decode(encoding) method. An encoding of 'latin-1' will directly turn a bytearray of 8-bit characters into a string without any modification of the underlying character values.

bytearray(s ,encoding)

An alternative calling convention for creating a bytearray instance from characters in a string s where encoding specifies the character encoding to use in the conversion.

bytes([x])

A type representing an immutable array of bytes. In Python 2, this is an alias for str() which creates a standard 8-bit string of characters. In Python 3, bytes is a completely separate type that is an immutable version of the bytearray type described earlier. In that case, the argument x has the same interpretation and can be used in the same manner. One portability caution is that even though bytes is defined in Python 2, the resulting object does not behave consistently with Python 3. For example, if a is an instance created by bytes(), then a[i] returns a character string in Python 2, but returns an integer in Python 3.

bytes(s, encoding)

An alternative calling convention for creating a bytes instance from characters in a string s where encoding specifies the character encoding to use. Python 3 only.

chr(x)

Converts an integer value, x, into a one-character string. In Python 2, x must be in the range 0 <= x <= 255, and in Python 3, x must represent a valid Unicode code point. If x is out of range, a ValueError exception is raised.

classmethod(func)

This function creates a class method for the function func. It is typically only used inside class definitions where it is implicitly invoked by the @classmethod decorator. Unlike a normal method, a class method receives the class as the first argument, not an instance. For example, if you had an object, f, that is an instance of class Foo, invoking a class method on f will pass the class Foo as the first argument to the method, not the instance f.

cmp(x, y)

Compares x and y and returns a negative number if x < y, a positive number if x > y, or 0 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.

compile(string, filename, kind [, flags [, dont_inherit]])

Compiles string into a code object for use with exec() or eval(). string is a string containing valid Python code. If this code spans multiple lines, the lines must be terminated by a single newline (' ') and not platform-specific variants (for example, ' ' on Windows). 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. The flags parameter determines which optional features (associated with the _ _future_ _ module) are enabled. Features are specified using the bitwise OR of flags defined in the _ _future_ _ module. For example, if you wanted to enable new division semantics, you would set flags to _ _future_ _.division.compiler_flag. If flags is omitted or set to 0, the code is compiled with whatever features are currently in effect. If flags is supplied, the features specified are added to those features already in effect. If dont_inherit is set, only those features specified in flags are enabled—features currently enabled are ignored.

complex([real [, imag]])

Type representing a complex number with real and imaginary components, real and imag, which can be supplied as any numeric type. If imag is omitted, the imaginary component is set to zero. If real is passed as a string, the string is parsed and converted to a complex number. In this case, imag should be omitted. If no arguments are given, 0j is returned.

delattr(object, attr)

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

dict([m]) or dict(key1 = value1, key2 = value2, ...)

Type representing a dictionary. If no argument is given, an empty dictionary is returned. If m is a mapping object (such as a dictionary), a new dictionary having the same keys and same values as m is returned. For example, if m is a dictionary, dict(m) simply makes a shallow copy of it. If m is not a mapping, it must support iteration in which a sequence of (key,value) pairs is produced. These pairs are used to populate the dictionary. dict() can also be called with keyword arguments. For example, dict(foo=3, bar=7) creates the dictionary { 'foo' : 3, 'bar' : 7 }.

dir([object])

Returns a sorted list of attribute names. If object is a module, it contains the list of symbols defined in that module. If object is a type or class object, it returns a list of attribute names. The names are typically obtained from the object’s _ _dict_ _ attribute if defined, but other sources may be used. If no argument is given, the names in the current local symbol table are returned. It should be noted that this function is primarily used for informational purposes (for example, used interactively at the command line). It should not be used for formal program analysis because the information obtained may be incomplete. Also, user-defined classes can define a special method _ _dir_ _() that alters the result of this function.

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. This function may not be called with complex numbers.

enumerate(iter[, initial value)

Given an iterable object, iter, returns a new iterator (of type enumerate) that produces tuples containing a count and the value produced from iter. For example, if iter produces a, b, c, then enumerate(iter) produces (0,a), (1,b), (2,c).

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

Evaluates an expression. expr is a string or a code object created by compile(). globals and locals are mapping objects that define the global and local namespaces, respectively, for the operation. If omitted, the expression is evaluated in the namespace of the caller. It is most common for globals and locals to be specified as dictionaries, but advanced applications can supply custom mapping objects.

exec(code [, global [, locals]])

Executes Python statements. code is a string, a file, or a code object created by compile(). globals and locals define the global and local namespaces, respectively, for the operation. If omitted, the code is executed in the namespace of the caller. If no global or local dictionaries are given, the behavior of this function is a little muddled between Python versions. In Python 2, exec is actually implemented as a special language statement, whereas Python 3 implements it as a standard library function. A subtle side effect of this implementation difference is that in Python 2, code evaluated by exec can freely mutate local variables in the caller’s namespace. In Python 3, you can execute code that makes such changes, but they don’t seem to have any lasting effect beyond the exec() call itself. This is because Python 3 uses locals() to obtain the local namespace if one isn’t supplied. As you will note in the documentation for locals(), the returned dictionary is only safe to inspect, not modify.

filter(function, iterable)

In Python 2, this creates a list consisting of the objects from iterable for which function evaluates to true. In Python 3, the result is an iterator that produces this result. If function is None, the identity function is used and all the elements of iterable that are false are removed. iterable can be any object that supports iteration. As a general rule, it is significantly faster to use a generator expression or list comprehension to filter data (refer to Chapter 6).

float([x])

Type representing a floating-point number. If x is a number, it is converted to a float. If x is a string, it is parsed into a float. If no argument is supplied, 0.0 is returned.

format(value [, format_spec])

Converts value to a formatted string according to the format specification string in format_spec. This operation invokes value._ _format_ _(), which is free to interpret the format specification as it sees fit. For simple types of data, the format specifier typically includes an alignment character of '<', '>’, or '^'; a number (which indicates the field width); and a character code of 'd', 'f', or 's' for integer, floating point, or string values, respectively. For example, a format specification of 'd' formats an integer, a specification of '8d' right aligns an integer in an 8-character field and '<8d' left aligns an integer in an 8-character field. More details on format() and format specifiers can be found in Chapter 3, “Types and Objects,” and Chapter 4, “Operators and Expressions.”

frozenset([items])

Type representing an immutable set object populated with values taken from items that must be an iterable. The values must also be immutable. If no argument is given, an empty set is returned.

getattr(object, name [,default])

Returns the value of a named attribute of an object. name is a string containing the attribute name. default is an optional value to return if no such attribute exists. Otherwise, AttributeError is raised. Same as object.name.

globals()

Returns the dictionary of the current module that represents the global namespace. When called inside another function or method, it returns the global namespace of the module in which the function or method was defined.

hasattr(object, name)

Returns True if name is the name of an attribute of object. False is returned otherwise. name is a string.

hash(object)

Returns an integer hash value for an object (if possible). The hash value is primarily used in the implementation of dictionaries, sets, and other mapping objects. The hash value is the same for any two objects that compare as equals. Mutable objects don’t define a hash value, although user-defined classes can define a method _ _hash_ _() to support this operation.

help([object])

Calls the built-in help system during interactive sessions. object may be a string representing the name of a module, class, function, method, keyword, or documentation topic. If it is any other kind of object, a help screen related to that object will be produced. If no argument is supplied, an interactive help tool will start and provide more information.

hex(x)

Creates a hexadecimal string from an integer x.

id(object)

Returns the unique integer identity of object. You should not interpret the return value in any way (that is, as a memory location).

input([prompt])

In Python 2, this prints a prompt, reads a line of input, and processes it through eval() (that is, it’s the same as eval(raw_input(prompt)). In Python 3, a prompt is printed to standard output and a single line of input is read without any kind of evaluation or modification.

int(x [,base])

Type representing an integer. If x is a number, it is converted to an integer by truncating toward 0. If it is a string, it is parsed into an integer value. base optionally specifies a base when converting from a string. In Python 2, a long integer is created if the value exceeds the 32-bit range of the int type.

isinstance(object, classobj)

Returns True if object is an instance of classobj, is a subclass of classobj, or belongs to an abstract base class classobj. The classobj parameter can also be a tuple of possible types or classes. For example, isinstance(s, (list,tuple)) returns True if s is a tuple or a list.

issubclass(class1, class2)

Returns True if class1 is a subclass of (derived from) class2 or if class1 is registered with an abstract base class class2. class2 can also be a tuple of possible classes, in which case each class will be checked. Note that issubclass(A, A) is true.

iter(object [,sentinel])

Returns an iterator for producing items in object. If the sentinel parameter is omitted, the object must either provide the method _ _iter_ _(), which creates an iterator, or implement _ _getitem_ _(), which accepts integer arguments starting at 0. If sentinel is specified, object is interpreted differently. Instead, object should be a callable object that takes no parameters. The returned iterator object will call this function repeatedly until the returned value is equal to sentinel, at which point iteration will stop. A TypeError will be generated if object does not support iteration.

len(s)

Returns the number of items contained in s. s should be a list, tuple, string, set, or dictionary. A TypeError is generated if s is an iterable such as a generator.

list([items])

Type representing a list. items may be any iterable object, the values of which are used to populate the list. If items is already a list, a copy is made. If no argument is given, an empty list is returned.

locals()

Returns a dictionary corresponding to the local namespace of the caller. This dictionary should only be used to inspect the execution environment—it is not safe to modify the contents of this dictionary.

long([x[, base]])

Type representing long integers in Python 2. If x is a number, it is converted to an integer by truncating toward 0. If x is a string, it is parsed into a long value. If no argument is given, this function returns 0L. For portability, you should avoid direct use of long. Using int(x) will create a long as necessary. For type checking, use isinstance(x, numbers.Integral) to check if x is any integer type.

map(function, items, ...)

In Python 2, this applies function to every item of items and returns a list of results. In Python 3, an iterator producing the same results is created. If multiple input sequences are supplied, function is assumed to take that many arguments, with each argument taken from a different sequence. The behavior when processing multiple input sequences differs between Python 2 and Python 3. In Python 2, the result is the same length as the longest input sequence with None used as a padding value when the shorter input sequences are exhausted. In Python 3, the result is only as long as the shortest sequence. The functionality provided by map() is almost always better expressed using a generator expression or list comprehension (both of which provide better performance). For example, map(function, s) can usually be replaced by [function(x) for x in s].

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

For a single argument, s, this function returns the maximum value of the items in s, which may be any iterable object. For multiple arguments, it returns the largest of the arguments.

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

For a single argument, s, this function returns the minimum value of the items in s, which may be any iterable object. For multiple arguments, it returns the smallest of the arguments.

next(s [, default])

Returns the next item from the iterator s. If the iterator has no more items, a StopIteration exception is raised unless a value is supplied to the default argument. In that case, default is returned instead. For portability, you should always use this function instead of calling s.next() directly on an iterator s. In Python 3, the name of the underlying iterator method changed to s._ _next_ _(). If you write your code to use the next() function, you won’t have to worry about this difference.

object()

The base class for all objects in Python. You can call it to create an instance, but the result isn’t especially interesting.

oct(x)

Converts an integer, x, to an octal string.

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

In Python 2, opens the file filename and returns a new file object (refer to Chapter 9, “Input and Output”). mode is a string that indicates how the file should be opened: 'r' for reading, 'w' for writing, and 'a' for appending. A second character 't' or 'b' is used to indicate text-mode (the default) or binary mode. For example, 'r' or 'rt' opens a file in text mode, whereas 'rb' opens a file in binary mode. 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. If a mode of 'U' or 'rU' is specified, the file is opened in universal newline mode. In this mode, all variants of a newline (' ', ' ', ' ') are converted to the standard ' ' character. If the mode is omitted, a mode of 'rt' 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).

open(filename [, mode [, bufsize [, encoding [, errors [, newline [, closefd]]]]]])

In Python 3, this opens the file filename and returns a file object. The first three arguments have the same meaning as for the Python 2 version of open() described earlier. encoding is an encoding name such as 'utf-8'. errors is the error handling policy and is one of 'strict', 'ignore', 'replace', 'backslashreplace', or 'xmlcharrefreplace'. newline controls the behavior of universal newline mode and is set to None, '', ' ', ' ', or ' '. closefd is a Boolean flag that specifies whether the underlying file descriptor is closed when the close() method executes. Unlike Python 2, different kinds of objects are returned depending on the selected I/O mode. For example, if you open a file in binary mode, you get an object where I/O operations such as read() and write() operate on byte arrays instead of strings. File I/O is one area where there are significant differences between Python 2 and 3. Consult Appendix A, “Python 3,” for more details.

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 single Unicode characters, a value in the range [0,65535] is usually returned. In Python 3, c may also be a Unicode surrogate pair, in which case it is converted into the appropriate Unicode code point.

pow(x, y [, z])

Returns x ** y. If z is supplied, this function returns (x ** y) % z. If all three arguments are given, they must be integers and y must be nonnegative.

print(value, ... [, sep=separator, end=ending, file=outfile])

Python 3 function for printing a series of values. As input, you can supply any number of values, all of which are printed on the same line. The sep keyword argument is used to specify a different separator character (a space by default). The end keyword argument specifies a different line ending (' ' by default). The file keyword argument redirects the output to a file object. This function can be used in Python 2 if you add the statement from _ _future_ _ import print_function to your code.

property([fget [,fset [,fdel [,doc]]]])

Creates a property attribute for classes. fget is a function that returns the attribute value, fset sets the attribute value, and fdel deletes an attribute. doc provides a documentation string. These parameters may be supplied using keyword arguments—for example, property(fget=getX, doc="some text").

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

In Python 2, this creates a fully populated 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. In Python 3, range() creates a special range object that computes its values on demand (like xrange() in previous Python versions).

raw_input([prompt])

Python 2 function that 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. Use input() to read input in Python 3.

repr(object)

Returns a string representation of object. In most cases, the returned string is an expression that can be passed to eval() to re-create the object. Be aware that in Python 3, the result of this function may be a Unicode string that can’t be displayed in the terminal or shell window (resulting in an exception). Use the ascii() function to create an ASCII representation of object.

reversed(s)

Creates a reverse iterator for sequence s. This function only works if s implements the sequence methods _ _len_ _() and _ _getitem_ _(). In addition, s must index items starting at 0. It does not work with generators or iterators.

round(x [, n])

Rounds 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, Python 2 rounds away from 0 (for example, 0.5 is rounded to 1.0 and -0.5 is rounded to -1.0). Python 3 rounds toward 0 if the previous digit is even and away from 0 otherwise (for example, 0.5 is rounded to 0.0 and 1.5 is rounded to 2).

set([items])

Creates a set populated with items taken from the iterable object items. The items must be immutable. If items contains other sets, those sets must be of type frozenset. If items is omitted, an empty set is returned.

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 the extended slice syntax a[i:i:k]. Refer to the section “Sequence and Mapping Methods” in Chapter 3 for details.

sorted(iterable [, key=keyfunc [, reverse=reverseflag]])

Creates a sorted list from items in iterable. The keyword argument key is a single-argument function that transforms values before they are passed to the compare function. The keyword argument reverse is a Boolean flag that specifies whether or not the resulting list is sorted in reverse order. The key and reverse arguments must be specified using keywords—for example, sorted(a,key=get_name).

staticmethod(func)

Creates a static method for use in classes. This function is implicitly invoked by the @staticmethod decorator.

str([object])

Type representing a string. In Python 2, a string contains 8-bit characters, whereas in Python 3 strings are Unicode. If object is supplied, a string representation of its value is created by calling its _ _str_ _() method. This is the same string that you see when you print the object. If no argument is given, an empty string is created.

sum(items [,initial])

Computes the sum of a sequence of items taken from the iterable object items. initial provides the starting value and defaults to 0. This function only works with numbers.

super(type [, object])

Returns an object that represents the superclasses of type. The primary purpose of this object is to invoke methods in base classes. Here’s an example:

image

If object is an object, then isinstance(object, type) must be true. If object is a type, then it must be a subclass of type. Refer to Chapter 7, “Classes and Object-Oriented Programming,” for more details. In Python 3, you can use super() in a method with no arguments. In this case, type is set to the class in which the method is defined and object is set to the first argument of the method. Although this cleans up the syntax, it’s not backwards-compatible with Python 2 so it should be avoided if you’re concerned about portability.

tuple([items])

Type representing a tuple. If supplied, items is an iterable object that is used to populate the tuple. However, if items is already a tuple, it’s simply returned unmodified. If no argument is given, an empty tuple is returned.

type(object)

The base class of all types in Python. When called as a function, returns the type of object. This type is the same as the object’s class. For common types such as integers, floats, and lists, the type will refer to one of the other built-in classes such as int, float, list, and so forth. For user-defined objects, the type is the associated class. For objects related to Python’s internals, you will typically get a reference to one of the classes defined in the types module.

type(name,bases,dict)

Creates a new type object (which is the same as defining a new class). name is the name of the type, bases is a tuple of base classes, and dict is a dictionary containing definitions corresponding to a class body. This function is most commonly used when working with metaclasses. This is described further in Chapter 7.

unichr(x)

Converts the integer or long integer x, where 0 <= x <= 65535, to a single Unicode character. Python 2 only. In Python 3, just use chr(x).

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

In Python 2, this 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', 'replace', 'backslashreplace', or 'xmlcharrefreplace'. Refer to Chapter 9 and Chapter 3 for details. Not available in Python 3.

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. The dictionary returned by this function should be assumed to be read-only. It’s not safe to modify its contents.

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

A type representing a range of integer values from start to stop that is not included. step provides an optional stride. The values are not actually stored but are computed on demand when accessed. In Python 2, xrange() is the preferred function to use when you want to write loops over ranges of integer values. In Python 3, xrange() has been renamed to range() and xrange() is unavailable. start, stop, and step are limited to the set of values supported by machine integers (typically 32 bits).

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

In Python 2, 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. If no arguments are given, an empty list is returned. In Python 3, the behavior is similar, but the result is an iterator that produces a sequence of tuples. In Python 2, be aware that using zip() with long input sequences is something that can unintentionally consume large amounts of memory. Consider using itertools.izip() instead.

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.

Exception Base Classes

The following exceptions serve as base classes for all the other exceptions:

BaseException

The root class for all exceptions. All built-in exceptions are derived from this class.

Exception

The base class for all program-related exceptions that includes all built-in exceptions except for SystemExit, GeneratorExit, and KeyboardInterrupt. User-defined exceptions should be defined by inheriting from Exception.

ArithmeticError

The base class for arithmetic exceptions, including OverflowError, ZeroDivisionError, and FloatingPointError.

LookupError

The base class for indexing and key errors, including IndexError and KeyError.

EnvironmentError

The 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:

image

Exception Instances

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. Here’s an example:

image

Instances of an exception e have a few standard attributes that can be useful to inspect and/or manipulate in certain applications.

e.args

The tuple of arguments supplied when raising the exception. In most cases, this is a one-item tuple with a string describing the error. For EnvironmentError exceptions, the value is a 2-tuple or 3-tuple containing an integer error number, a string error message, and an optional filename. The contents of this tuple might be useful if you need to re-create the exception in a different context; for example, to raise an exception in a different Python interpreter process.

e.message

A string representing the error message that gets printed when the exception is displayed (Python 2 only).

e._ _cause_ _

Previous exception when using explicit chained exceptions (Python 3 only). See Appendix A.

e._ _context_ _

Previous exception for implicitly chained exceptions (Python 3 only). See Appendix A.

e._ _traceback_ _

Traceback object associated with the exception (Python 3 only). See Appendix A.

Predefined Exception Classes

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(). It should be noted that most other I/O operations such as the read() and readline() methods of files return an empty string to signal EOF instead of raising an exception.

FloatingPointError

Failed floating-point operation. It should be noted that floating-point exception-handling is a tricky problem and only that this exception only gets raised if Python has been configured and built in a way that enables it. It is more common for floating-point errors to silently produce results such as float('nan') or float('inf'). A subclass of ArithmeticError.

GeneratorExit

Raised inside a generator function to signal termination. This happens when a generator is destroyed prematurely (before all generator values are consumed) or the close() method of a generator is called. If a generator ignores this exception, the generator is terminated and the exception is silently ignored.

IOError

Failed I/O operation. The value is an IOError instance with the 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 mapping. 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 an integer value being too large to be represented. This exception usually only arises if large integer values are passed to objects that internally rely upon fixed-precision machine integers in their implementation. For example, this error can arise with range or xrange objects if you specify starting or ending values that exceed 32 bits in size. A subclass of ArithmeticError.

ReferenceError

Result of accessing a weak reference after the underlying object has been destroyed. See the weakref module.

RuntimeError

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

StopIteration

Raised to signal the end of iteration. This normally happens in the next() method of an object or in a generator function.

SyntaxError

Parser syntax error. Instances have the attributes filename, lineno, offset, and text, which 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

Occurs when an operation or a function is applied to an object of an 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.

UnicodeEncodeError

Unicode encoding error. A subclass of UnicodeError.

UnicodeDecodeError

Unicode decoding error. A subclass of UnicodeError.

UnicodeTranslateError

Unicode error occurred during translation. A subclass of UnicodeError.

ValueError

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

WindowsError

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

ZeroDivisionError

Dividing by zero. A subclass of ArithmeticError.

Built-In Warnings

Python has a warnings module that is typically used to notify programmers about deprecated features. Warnings are issued by including code such as the following:

image

Although warnings are issued by a library module, the names of the various warnings are built-in. Warnings are somewhat similar to exceptions. There is a hierarchy of built-in warnings that all inherit from Exception.

Warning

The base class of all warnings. A subclass of Exception.

UserWarning

A generic user-defined warning. A subclass of Warning.

DeprecationWarning

A warning for deprecated features. A subclass of Warning.

SyntaxWarning

A warning for deprecated Python syntax. A subclass of Warning.

RuntimeWarning

A warning for potential runtime problems. A subclass of Warning.

FutureWarning

A warning that the behavior of a feature will change in the future. A subclass of Warning.

Warnings are different than exceptions in that the issuing of a warning with the warn() function may or may not cause a program to stop. For example, a warning may just print something to the output or it may raise an exception. The actual behavior can be configured with the warnings module or with the -W option to the interpreter. If you are using someone else’s code that generates a warning, but you would like to proceed anyways, you can catch warnings that have been turned into exceptions using try and except. For example:

image

It should be emphasized that code such as this is rare. Although it will catch a warning that has been turned into an exception, it doesn’t suppress warning messages (you have to use the warnings module to control that). Plus, ignoring warnings is a good way to write code that doesn’t work correctly when new versions of Python are released.

future_builtins

The future_builtins module, only available in Python 2, provides implementations of the built-in functions whose behavior is changed in Python 3. The following functions are defined:

ascii(object)

Produces the same output as repr(). Refer to the description in the “Built-In Functions” section of this chapter.

filter(function, iterable)

Creates an iterator instead of a list. The same as itertools.ifilter().

hex(object)

Creates a hexadecimal string, but uses the _ _index_ _() special method to get an integer value instead of calling _ _hex_ _().

map(function, iterable, ...)

Creates an iterator instead of a list. The same as itertools.imap().

oct(object)

Creates an octal string, but uses the _ _index_ _() special method to get an integer value instead of calling _ _oct_ _().

zip(iterable, iterable, ... )

Creates an iterator instead of a list. The same as itertools.izip().

Be aware that the functions listed in this module are not a complete list of changes to the built-in module. For instance, Python 3 also renames raw_input() to input() and xrange() to range().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.74.231