Built-in Functions

All built-in names (functions, exceptions, and so on) exist in the implied outer built-in scope, which corresponds to the builtins module (named __builtin__ in Python 2). Because this scope is always searched last on name lookups, these functions are always available in programs without imports. However, their names are not reserved words and might be hidden by assignments to the same name in global or local scopes.

abs(N)

Returns the absolute value of a number N.

all(iterable)

Returns True only if all elements of the iterable are true.

any(iterable)

Returns True only if any element of the iterable is true.

ascii(object)

Like repr(), returns a string containing a printable representation of an object, but escapes the non-ASCII characters in the repr() result string using x, u, or U escapes. This result is similar to that returned by repr() in Python 2.X.

bin(N)

Convert an integer number to a binary (base 2) digits string. The result is a valid Python expression. If argument N is not a Python int object, it must define an __index__() method that returns an integer. See also int(x, 2) to convert from binary, 0bNNN binary literals, and the b type code in str.format().

bool([x])

Converts a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise, it returns True. bool is also a class, which is a subclass of int. The class bool cannot be subclassed further. Its only instances are False and True.

bytearray([arg [, encoding [, errors]]])

Returns a new array of bytes. The bytearray type is a mutable sequence of small integers in the range 0...255, which prints as ASCII text when possible. It is essentially a mutable variant of bytes, which supports most operations of mutable sequences, as well as most methods of the str string type. arg may be a str string with encoding name (and optionally errors) as in str(); an integer size to initialize an array of NULL bytes; an iterable of small integers used to initialize the array such as a bytes string or another bytearray; an object conforming to the memory-view (previously known as buffer) interface used to initialize the array; or absent, to create a zero-length array.

bytes([arg [, encoding [, errors]]])

Returns a new bytes object, which is an immutable sequence of integers in the range 0...255. bytes is an immutable version of bytearray. It has the same nonmutating string methods and sequence operations. It is commonly used to represent 8-bit byte strings of binary data. Constructor arguments are interpreted as for bytearray(). bytes objects may also be created with the b'ccc' literal.

chr(I)

Returns a one-character string whose Unicode codepoint is integer I. This is the inverse of ord() (e.g., chr(97) is 'a' and ord('a') is 97).

classmethod(function)

Returns a class method for a function. A class method receives the class as an implicit first argument, just like an instance method receives the instance. Use the @classmethod function decorator in version 2.4 and later (see the section The def Statement).

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

Compiles string into a code object. string is a Python string containing Python program code. filename is a string used in error messages (and is usually the name of the file from which the code was read, or <string> if typed interactively). kind can be 'exec' if string contains statements; 'eval' if string is an expression; or 'single', which prints the output of an expression statement that evaluates to something other than None. The resulting code object can be executed with exec() or eval() built-in function calls. The optional last two arguments control which future statements affect the string’s compilation; if absent, the string is compiled with the future statements in effect at the place of the compile() call (see Python manuals for more details).

complex([real [, imag]])

Builds a complex number object (this can also be done using the J or j suffix: real+imagJ). imag defaults to 0. If both arguments are omitted, returns 0j.

delattr(object, name)

Deletes the attribute named name (a string) from object. It is similar to del obj.name, but name is a string, not a variable (e.g., delattr(a,'b') is like del a.b).

dict([mapping | iterable | keywords])

Returns a new dictionary initialized from a mapping; a sequence (or other iterable) of key/value pairs; or a set of keyword arguments. If no argument is given, it returns an empty dictionary. This is a subclassable type class name.

dir([object])

If no arguments, this returns the list of names in the current local scope (namespace). With any object with attributes as an argument, it returns the list of attribute names associated with that object. It works on modules, classes, and class instances, as well as built-in objects with attributes (lists, dictionaries, etc.). Its result includes inherited attributes, and is sorted. Use __dict__ attributes for simple attribute lists of a single object (and possibly __slots__ for some classes).

divmod(X, Y)

Returns a tuple of (X / Y, X % Y).

enumerate(iterable, start=0)

Returns an iterable enumerate object. iterable must be a sequence, an iterator, or some other object that supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start, or zero by default) and the corresponding value obtained from iterating over iterable. This call is useful for obtaining an indexed series when both positions and items are required in for loops: (0, seq[0]), (1, seq[1]), (2, seq[2]).... Available in version 2.3 and later.

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

Evaluates expr, which is assumed to be either a Python string containing a Python expression or a compiled code object. expr is evaluated in the namespace scopes of the eval call itself, unless the globals and/or locals namespace dictionary arguments are passed. locals defaults to globals if only globals is passed. It returns an expr result. Also see the compile function discussed earlier in this section, and the exec() built-in for dynamically running statements.

exec(stmts [, globals [, locals]])

Evaluates stmts, which is assumed to be either a Python string containing Python statements or a compiled code object. If stmts is a string, the string is parsed as a suite of Python statements, which is then executed unless a syntax error occurs. If it is a code object, it is simply executed. globals and locals work the same as in eval(), and compile() may be used to precompile to code objects. This is available as a statement form in Python 2.X (see Specific Statements).

filter(function, iterable)

Returns those elements of iterable for which function returns true. function takes one parameter. If function is None, this returns all the true items.

In Python 2.6 this call returns a list. In Python 3.0, it returns an iterable object that generates values on demand and can be traversed only once (wrap in a list() call to force results generation if required).

float([X])

Converts a number or a string X to a floating-point number (or 0.0 if no argument is passed). This is a subclassable type class name.

format(value [, formatspec])

Converts an object value to a formatted representation, as controlled by string formatspec. The interpretation of formatspec depends on the type of the value argument (a standard formatting syntax is used by most built-in types, described for the string formatting method earlier in this book). format(value, formatspec) calls value.__format__(formatspec), and is a base operation of the str.format method (e.g., format(1.3333, '.2f') is equivalent to '{0:.2f}'.format(1.3333)).

frozenset([iterable])

Returns a frozen set object whose elements are taken from iterable. Frozen sets are immutable sets that have no update methods, and may be nested in other sets.

getattr(object, name [, default])

Returns the value of attribute name (a string) from object. It is similar to object.name, but name is a string, not a variable (e.g., getattr(a,'b') is like a.b). If the named attribute does not exist, default is returned if provided; otherwise, AttributeError is raised.

globals()

Returns a dictionary containing the caller’s global variables (e.g., the enclosing module’s names).

hasattr(object, name)

Returns true if object has an attribute called name (a string); false otherwise.

hash(object)

Returns the hash value of object (if it has one). Hash values are integers used to quickly compare dictionary keys during a dictionary lookup.

help([object])

Invokes the built-in help system. (This function is intended for interactive use.) If no argument is given, an interactive help session starts in the interpreter console. If the argument is a string, it is looked up as the name of a module, function, class, method, keyword, or documentation topic, and its help text is displayed. If the argument is any other kind of object, help for that object is generated.

hex(N)

Converts an integer number N to a hexadecimal (base 16) digits string. If argument N is not a Python int object, it must define an __index__() method that returns an integer.

id(object)

Returns the unique identity integer of object (i.e., its address in memory).

__import__(name [, globals [, locals [, fromlist [, level] ]]])

Imports and returns a module, given its name as a string at runtime (e.g., mod = __import__("mymod")). This call is generally faster than constructing and executing an import statement string with exec(). This function is called by import and from statements internally and can be overridden to customize import operations. All arguments but the first have advanced roles (see the Python Library Reference). See also the imp standard library module for related tools.

input([prompt])

Prints a prompt string if given, then reads a line from the stdin input stream (sys.stdin) and returns it as a string. It strips the trailing at the end of the line and raises EOFError at the end of the stdin stream. On platforms where GNU readline is supported, input() uses it. In Python 2.X, this function is named raw_input().

int([number | string [, base]])

Converts a number or string to a plain integer. Conversion of floating-point numbers to integers truncates toward 0. base can be passed only if the first argument is a string, and defaults to 10. If base is passed as 0, the base is determined by the string’s contents; otherwise, the value passed for base is used for the base of the conversion of the string. base may be 0, and 2...36. The string may be preceded by a sign and surrounded by whitespace. If no arguments, returns 0. This is a subclassable type class name.

isinstance(object, classinfo)

Returns true if object is an instance of classinfo, or an instance of any subclass thereof. classinfo can also be a tuple of classes and/or types. In Python 3.0, types are classes, so there is no special case for types. In Python 2.X, the second argument can also be a type object, making this function useful as an alternative type-testing tool (isinstance(X, Type) versus type(X) is Type).

issubclass(class1, class2)

Returns true if class1 is derived from class2. class2 can also be a tuple of classes.

iter(object [, sentinel])

Returns an iterator object that can be used to step through items in object. Iterator objects returned have a __next__() method that returns the next item or raises StopIteration to end the progression. All iteration contexts in Python use this protocol to advance, if supported by object. The next(I) built-in function also calls I.__next__() automatically. If one argument, object is assumed to provide its own iterator or be a sequence; if two arguments, object is a callable that is called until it returns sentinel. The iter() call can be overloaded in classes with __iter__.

In Python 2.X, iterable objects have a method named next() instead of __next__(). For forward compatibility, the next() built-in function is available in 2.6 and calls I.next() instead of I.__next__() (prior to 2.6, I.next() may be called manually instead).

len(object)

Returns the number of items (length) in a collection object, which may be a sequence or mapping.

list([iterable])

Returns a new list containing all the items in any iterable object. If iterable is already a list, it returns a copy of it. If no arguments, returns a new empty list. This is a subclassable type class name.

locals()

Returns a dictionary containing the local variables of the caller (with one key:value entry per local).

map(function, iterable [, iterable]*)

Applies function to each item of any sequence or other iterable iterable, and returns the individual results. For example, map(abs, (1, −2)) returns 1 and 2. If additional iterable arguments are passed, function must take that many arguments, and it is passed one item from each iterable on every call; iteration stops at the end of the shortest iterable.

In Python 2.6, this returns a list of the individual call results. In Python 3.0, it instead returns an iterable object that generates results on demand and can be traversed only once (wrap it in a list() call to force results generation if required). Also in Python 2.X (but not Python 3), if function is None, map collects all the items into a result list; if sequences differ in length, all are padded to the length of the longest, with Nones. Similar utility is available in Python 3.0 in module itertools.

max(iterable [, arg]* [, key])

With a single argument iterable, returns the largest item of a nonempty iterable (e.g., string, tuple, and list). With more than one argument, it returns the largest of all the arguments. The optional keyword-only key argument specifies a one-argument value transform function like that used for list.sort() and sorted().

memoryview(object)

Returns a memory view object created from the given argument. Memory views allow Python code to access the internal data of an object that supports the protocol without copying the object. Memory can be interpreted as simple bytes or more complex data structures. Built-in objects that support the memory-view protocol include bytes and bytearray. See Python manuals; memory views are largely a replacement for the Python 2.X buffer protocol and built-in function.

min(iterable [, arg]* [, key])

With a single argument iterable, returns the smallest item of a nonempty iterable (e.g., string, tuple, list). With more than one argument, it returns the smallest of all the arguments. The key argument is as in max().

next(iterator [, default])

Retrieves the next item from the iterator by calling its __next__() method. If the iterator is exhausted, default is returned if given; otherwise, StopIteration is raised.

This is available in Python 2.6 for forward compatibility, but it calls iterator.next() instead of iterator.__next__(). In Python 2.X prior to 2.6, this call is missing; use iterator.next() manually instead.

object()

Returns a new featureless object. object is a base for all new style classes, which includes classes explicitly derived from object in Python 2.X, and all classes in Python 3.0.

oct(N)

Converts a number N to an octal (base 8) digits string. If argument N is not a Python int object, it must define a __index__() method that returns an integer.

open(…)

open(file [, mode='r' 
   [, buffering=None 
   [, encoding=None        # text mode only 
   [, errors=None          # text mode only 
   [, newline=None         # text mode only 
   [, closefd=True] ]]]]]) # descriptors only

See also Python 2.X open() on page 123. Returns a new file object connected to the external file named by file, or raises IOError if the open fails. file is usually a string or bytes object giving the name (and the path if the file isn’t in the current working directory) of the file to be opened. file may also be an integer file descriptor of the file to be wrapped. If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False. All options may be passed as keyword arguments.

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r', which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), and 'a' for appending. In text mode, if encoding is not specified, the encoding used is platform dependent, and newlines are translated to and from ' ' by default. For reading and writing raw bytes, use binary modes 'rb', 'wb', or 'ab', and leave encoding unspecified.

Available modes that may be combined: 'r' for read (default); 'w' for write, truncating the file first; 'a' for write, appending to the end of the file if it exists; 'b' for binary mode; 't' for text mode (default); '+' to open a disk file for updating (reading and writing); 'U' for universal newline mode (for backward compatibility, not needed for new code). The default 'r' mode is the same as 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation.

Python distinguishes between files opened in binary and text modes, even when the underlying operating system does not.[5]

  • For input, files opened in binary mode (by appending 'b' to mode) return contents as bytes objects without any Unicode decoding or line-end translations. In text mode (the default, or when 't' is appended to mode), the contents of the file are returned as str strings after the bytes are decoded using either an explicitly passed encoding name or a platform-dependent default, and line-ends are translated per newline.

  • For output, binary mode expects a bytes or bytearray and writes it unchanged. Text mode expects a str, and encodes it per encoding and applies line-end translations per newline before writing.

buffering is an optional integer used to set buffering policy. By default, full buffering is on. Pass 0 to switch buffering off (allowed in binary mode only); 1 to set line buffering; and an integer > 1 for full buffering. Buffered data transfers might not be immediately fulfilled (use file.flush to force).

encoding is the name of the encoding used to decode or encode a text file’s content on transfers. This should be used in text mode only. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding errors are to be handled. This should be used in text mode only. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. Ignoring encoding errors can lead to data loss. See codecs.register() for a list of the permitted values.

newline controls how universal newlines work, and applies to text mode only. It can be None (the default), '', ' ', ' ', and ' '.

  • On input, if newline is None, universal newlines mode is enabled: lines may end in ' ', ' ', or ' ', and all these are translated to ' ' before being returned to the caller. If newline is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

  • On output, if newline is None, any ' ' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If it is any of the other legal values, any ' ' characters written are translated to the given string.

If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given as a string and must be True (the default) in that case.

ord(C)

Returns an integer codepoint value of a one-character string C. For ASCII characters, this is the 7-bit ASCII code of C; for wider Unicode, this is the Unicode code point of a one-character Unicode string.

pow(X, Y [, Z])

Returns X to power Y [modulo Z]. It is similar to the ** expression operator.

print([object,...][, sep=' '] [, end=' '] [, file=sys.stdout])

Prints object(s) to the stream file, separated by sep and followed by end. sep, end, and file, if present, must be given as keyword arguments, and default as shown.

All nonkeyword arguments are converted to strings, like str() does, and written to the stream. Both sep and end must either be strings, or None (meaning use their default values). If no object is given, end is written. file must be an object with a write(string) method, but need not be an actual file; if it is not passed or is None, sys.stdout will be used. Print functionality is available as a statement form in Python 2.X (see Specific Statements).

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

Returns a property attribute for new-style classes (classes that derive from object). fget is a function for getting an attribute value, fset is a function for setting, and fdel is a function for deleting. This call may be used as a function decorator itself, and returns an object with methods getter, setter, and deleter, which may also be used as decorators in this role (see The def Statement).

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

Returns successive integers between start and stop. With one argument, it returns integers from zero through stop-1. With two arguments, it returns integers from start through stop-1. With three arguments, it returns integers from start through stop-1, adding step to each predecessor in the result. start, step default to 0, 1. range(0, 20, 2) is a list of even integers from 0 through 18. This call is often used to generate offset lists or repeat counts in for loops.

In Python 2.6 this call returns a list. In Python 3.0, it returns an iterable object that generates values on demand and can be traversed multiple times (wrap in a list() call to force results generation if required).

repr(object)

Returns a string containing a printable and potentially parseable as-code representation of any object. In Python 2.X (but not Python 3.0) this is equivalent to `object` (back quotes expression).

reversed(seq)

Returns a reverse iterator. seq must be an object that has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).

round(X [, N])

Returns the floating-point value X rounded to N digits after the decimal point. N defaults to zero, and may be negative to denote digits to the left of the decimal point. The return value is an integer if called with one argument, otherwise of the same type as X. In Python 2.X only, the result is always a floating-point. In Python 3.0 only, calls X.__round__().

set([iterable])

Returns a set whose elements are taken from iterable. The elements must be immutable. To represent sets of sets, the nested sets should be frozenset objects. If iterable is not specified, this returns a new empty set. Available since version 2.4. See also the section Sets, and the {...} set literal in Python 3.0.

setattr(object, name, value)

Assigns value to the attribute name (a string) in object. Like object.name = value, but name is a runtime string, not a variable name taken literally (e.g., setattr(a,'b',c) is equivalent to a.b=c).

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

Returns a slice object representing a range, with read-only attributes start, stop, and step, any of which can be None. Arguments are the same as for range. Slice objects may be used in place of i:j:k slice notation (e.g., X[i:j] is equivalent to X[slice(i, j)]).

sorted(iterable, key=None, reverse=False)

Returns a new sorted list from the items in iterable. The optional keyword arguments key and reverse have the same meaning as those for the list.sort() method described earlier; key is a one-argument value transform function. This works on any iterable and returns a new object instead of changing a list in-place, and is thus useful in for loops to avoid splitting sort calls out to separate statements due to None returns. Available in version 2.4 and later.

In Python 2.X, this has call signature sorted(iterable, cmp=None, key=None, reverse=False), where optional arguments cmp, key, and reverse have the same meaning as those for the Python 2.X list.sort() method described earlier in this book.

staticmethod(function)

Returns a static method for function. A static method does not receive an implicit first argument, and so is useful for processing class attributes that span instances. Use the @staticmethod function decorator in version 2.4 and later (see the section The def Statement).

str([object [, encoding [, errors]]])

Returns a “user-friendly” and printable string version of an object. This is also a subclassable type name. Operates in one of the following modes:

  • When only object is given, this returns its nicely printable representation. For strings, this is the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. With no arguments, this returns the empty string.

  • If encoding and/or errors are passed, this will decode the object, which can either be a byte string or a character buffer, using the codec for encoding. The encoding parameter is a string giving the name of an encoding; if the encoding is not known, LookupError is raised. Error handling is done according to errors; if errors is 'strict' (the default), a ValueError is raised for encoding errors, while a value of 'ignore' causes errors to be silently ignored, and a value of 'replace' causes the official Unicode replacement character, U+FFFD, to be used to replace input characters that cannot be decoded. See also the codecs module, and the similar bytes.decode() method (b'axe4'.decode('latin-1') is equivalent to str(b'axe4', 'latin-1')).

In Python 2.X, this call has simpler signature str([object]), and returns a string containing the printable representation of object (the first usage mode in Python 3.0).

sum(iterable [, start])

Sums start and the items of an iterable, from left to right, and returns the total. start defaults to 0. The iterable’s items are normally numbers and are not allowed to be strings (to concatenate an iterable of strings, use ''.join(iterable)).

super([type [, object-or-type]])

Returns the superclass of type. If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. Calling super() without arguments is equivalent to super(this_class, first_arg). In a single-inheritance class hierarchy, this call can be used to refer to parent classes without naming them explicitly. This call can also be used to implement cooperative multiple inheritance in a dynamic execution environment.

This works only for new-style classes in Python 2.X (where type is not optional), and for all classes in Python 3.0.

tuple([iterable])

Returns a new tuple with the same elements as any iterable passed in. If iterable is already a tuple, it is returned directly (not a copy). If no argument, returns a new empty tuple. This is also a subclassable type class name.

type(object | (name, bases, dict))

This call is used in two different modes, determined by call pattern:

  • With one argument, returns a type object representing the type of object. Useful for type-testing in if statements (e.g., type(X)==type([])), as well as dictionary keys. See also module types for preset type objects that are not built-in names, and isinstance() earlier in this section. Due to the recent merging of types and classes, type(object) is generally the same as object.__class__. In Python 2.X, the types module also includes built-in types.

  • With three arguments, serves as a constructor, returning a new type object. This is a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute. class X(object): a = 1 is equivalent to X = type('X', (object,), dict(a=1)). This mapping is commonly used for metaclass construction.

vars([object])

Without arguments, returns a dictionary containing the current local scope’s names. With a module, class, or class instance object as an argument, it returns a dictionary corresponding to object’s attribute namespace (i.e., its __dict__). The result should not be modified. Useful for % string formatting.

zip([iterable [, iterable]*])

Returns a series of tuples, where each ith tuple contains the ith element from each of the argument iterables. For example, zip('ab', 'cd') returns ('a', 'c') and ('b', 'd'). At least one iterable is required, or the result is empty. The result series is truncated to the length of the shortest argument iterable. With a single iterable argument, it returns a series of one-tuples. May also be used to unzip zipped tuples: X, Y = zip(*zip(T1, T2)).

In Python 2.6, this returns a list. In Python 3.0, it returns an iterable object that generates values on demand and can be traversed only once (wrap in a list() call to force results generation if required). In Python 2.X (but not Python 3), when there are multiple argument iterables of the same length, zip is similar to map with a first argument of None.

Python 2.X Built-in Functions

The prior section’s list applies to Python 3. Semantic differences between built-ins available in both Python 3.0 and 2.X are noted in the prior section.

Python 3.0 built-ins not supported by Python 2.6

Python 2.X does not have the following Python 3.0 built-in functions:

  • ascii() (this works like Python 2’s repr())

  • exec() (this is a statement form in Python 2.X with similar semantics)

  • memoryview()

  • print() (present in Python 2’s __builtin__ module, but not directly usable syntactically, as printing is a statement form and reserved word in Python 2.X)

Python 2.6 built-ins not supported by Python 3.0

Python 2.X has the following additional built-in functions, some of which are available in different forms in Python 3.0:

apply(func, pargs [, kargs])

Calls any callable object func (a function, method, class, etc.), passing the positional arguments in tuple pargs, and the keyword arguments in dictionary kargs. It returns the func call result.

In Python 3.0, this is removed. Use the argument-unpacking call syntax instead: func(*pargs, **kargs). This form is also preferred in Python 2.6 as it is more general and symmetric with function definitions.

basestring()

The baseclass for normal and Unicode strings (useful for isinstance tests).

In Python 3.0, the single str type represents all text (wide Unicode and other).

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

Returns a new buffer object for a conforming object (see the Python Library Reference).

This call is removed in Python 3.0. The new memoryview() built-in provides similar functionality.

callable(object)

Returns 1 if object is callable; otherwise, returns 0.

This call is removed in Python 3.0. Use hasattr(f, '__call__') instead.

cmp(X, Y)

Returns a negative integer, zero, or a positive integer to designate X < Y, X == Y, or X > Y, respectively.

In Python 3.0, this is removed, but may be simulated as: (X > Y) - (X < Y). However, most common cmp() use cases (comparison functions in sorts, and the __cmp__ method of classes) have also been removed in Python 3.0.

coerce(X, Y)

Returns a tuple containing the two numeric arguments X and Y converted to a common type.

This call is removed in Python 3.0 (its main use case was for Python 2.X classic classes).

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

Like eval, but runs all the code in a file whose string name is passed in as filename (instead of an expression). Unlike imports, this does not create a new module object for the file. It returns None. Namespaces for code in filename are as for eval.

In Python 3.0, this may be simulated as: exec(open(filename).read()).

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

An alias for the open() built-in function, and the subclassable class name of the built-in file type.

In Python 3.0, the name file is removed: use open() to create file objects, and io module classes to customize file operation.

input([prompt]) (original form)

Prints prompt, if given. Then it reads an input line from the stdin stream (sys.stdin), evaluates it as Python code, and returns the result. It is like eval(raw_input(prompt)).

In Python 3.0, because raw_input() was renamed input(), the original Python 2.X input() is no longer available, but may be simulated as: eval(input{prompt)).

intern(string)

Enters string in the table of “interned strings” and returns the interned string. Interned strings are “immortals” and serve as a performance optimization (they can be compared by fast is identity, rather than == equality).

In Python 3.0, this call has been moved to sys.intern(). Import module sys to use it.

long(X [, base])

Converts a number or a string X to a long integer. base can be passed only if X is a string. If 0, the base is determined by the string contents; otherwise, it is used for the base of the conversion. It is a subclassable type class name.

In Python 3.0, the int integer type supports arbitrarily long precision, and so subsumes Python 2’s long type. Use int() in Python 3.0.

raw_input([prompt])

This is the Python 2.X name of the Python 3.0 input() function described in the prior section.

In Python 3.0, use the input() built-in.

reduce(func, iterable [, init])

Applies the two-argument function func to successive items from iterable, so as to reduce the collection to a single value. If init is given, it is prepended to iterable.

In Python 3.0, this built-in is still available, as functools.reduce(). Import module functools to use it.

reload(module)

Reloads, re-parses, and re-executes an already imported module in the module’s current namespace. Re-execution replaces prior values of the module’s attributes in-place. module must reference an existing module object; it is not a new name or a string. This is useful in interactive mode if you want to reload a module after fixing it, without restarting Python. It returns the module object.

In Python 3.0, this built-in is still available as imp.reload(). Import module imp to use it.

unichr(i)

Returns the Unicode string of one character whose Unicode code is the integer i (e.g., unichr(97) returns the string u'a'). This is the inverse of ord for Unicode strings, and the Unicode version of chr(). The argument must be in range 0...65535 inclusive, or ValueError is raised.

In Python 3.0, normal strings represent Unicode characters: use the chr() call instead (e.g., ord('xe4') is 228, and chr(228) and chr(0xe4) both return 'ä').

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

Decodes string using the codec for encoding. Error handling is done according to errors. The default behavior is to decode UTF-8 in strict mode, meaning that encoding errors raise ValueError. See also the codecs module in the Python Library Reference.

In Python 3.0, there is no separate type for Unicode—the str type represents all text (wide Unicode and other), and the bytes type represents 8-bit byte binary data. Use normal str strings for Unicode text; bytes.decode() or str() to decode from raw bytes to Unicode according to an encoding; and normal file objects to process Unicode text files.

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

Like range, but doesn’t actually store the entire list all at once (rather, it generates one integer at a time). This is useful in for loops when there is a big range and little memory. It optimizes space, but generally has no speed benefit.

In Python 3.0, the original range() function is changed to return an iterable instead of producing a result list in memory, and thus subsumes Python 2’s xrange(). Use range() in Python 3.0.

In addition, the file open call has changed radically enough in Python 3.0 that individual mention of Python 2’s variant is warranted (in Python 2.X, codecs.open has many of the features in Python 3’s open):

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

Returns a new file object connected to the external file named filename (a string), or raises IOError if the open fails. The file name is mapped to the current working directory, unless it includes a directory path prefix. The first two arguments are generally the same as those for C’s fopen function, and the file is managed by the stdio system. With open(), file data is always represented as a normal str string in your script, containing bytes from the file (codecs.open() interprets file content as encoded Unicode text, represented as unicode objects).

mode defaults to 'r' if omitted, but can be 'r' for input; 'w' for output (truncating the file first); 'a' for append; and 'rb', 'wb', or 'ab' for binary files (to suppress line-end conversions to and from ). On most systems, most of these can also have a + appended to open in input/output updates mode (e.g., 'r+' to read/write, and 'w+' to read/write but initialize the file to empty).

bufsize defaults to an implementation-dependent value, but can be 0 for unbuffered, 1 for line-buffered, negative for system-default, or a given specific size. Buffered data transfers might not be immediately fulfilled (use file flush methods to force).



[5] In fact, because file mode implies both configuration options and string data types, it’s probably best to think of open() in terms of two distinct flavors—text and binary, as specified in the mode string. Python developers chose to overload a single function to support the two file types, with mode-specific arguments and differing content types, rather than provide two separate open functions and file object types.

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

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