8.2 Built-in Functions

This section documents the Python functions available in module _ _builtin_ _ in alphabetical order. Note that the names of these built-ins are not reserved words. Thus, your program can bind for its own purposes, in local or global scope, an identifier that has the same name as a built-in function. Names bound in local or global scope have priority over names bound in built-in scope, so local and global names hide built-in ones. You can also rebind names in built-in scope, as covered in Chapter 7. You should avoid hiding built-ins that your code might need.

_ _import_ _

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

Loads the module named by string module_name and returns the resulting module object. globals, which defaults to the result of globals( ), and locals, which defaults to the result of locals( ) (both covered in this section), are dictionaries that _ _import_ _ treats as read-only and uses only to get context for package-relative imports, covered in Section 7.3. fromlist defaults to an empty list, but can be a list of strings that name the module attributes to be imported in a from statement. See Section 7.2 for more details on module loading.

In practice, when you call _ _import_ _, you generally pass only the first argument, except in the rare and dubious case in which you use _ _import_ _ for a package-relative import. When you replace the built-in _ _import_ _ function with your own in order to provide special import functionality, you may have to take globals, locals, and fromlist into account.



Returns the absolute value of number x. When x is complex, abs returns the square root of x.imag**2+x.real**2. Otherwise, abs returns -x if x is less than 0, or x if x is greater than or equal to 0. See also _ _abs_ _ in Chapter 5.


apply(func,args=(  ),keywords={  })

Calls a function (or other callable object) and returns its result. apply's behavior is exactly the same as func(*args,**keywords). The * and ** forms are covered in Section 4.10 in Chapter 4. In almost all cases of practical interest, you can just use the syntax func(*args,**keywords) and avoid apply.

bool Python 2.2 and later


Returns 0, also known as False, if argument x evaluates as false; returns 1, also known as True, if argument x evaluates as true. See also Section 4.2.6 in Chapter 4. In Python 2.3, bool becomes a type (a subclass of int), and built-in names False and True refer to the only two instances of type bool. They are still numbers with values of 0 and 1 respectively, but str(True) becomes 'True', and str(False) becomes 'False', while in Python 2.2 the corresponding strings are '0' and '1' respectively.



Creates and returns a buffer object referring to obj's data. obj must be of a type that supports the buffer call interface, such as a string or array. For more on buffer, see Chapter 13.



Returns True if obj can be called, otherwise False. An object can be called if it is a function, method, class, type, or an instance with a _ _call_ _ method. See also _ _call_ _ in Chapter 5.



Returns a string of length 1, a single character corresponding to integer code in the ASCII/ISO encoding. See also ord and unichr in this section.



Returns 0 when x equals y, -1 when x is less than y, or 1 when x is greater than y. See also _ _cmp_ _ in Chapter 5.



Returns a pair whose two items are numbers x and y converted to a common type. See Section 4.5.1.



Compiles a string and returns a code object usable by exec or eval. compile raises SyntaxError when string is not syntactically valid Python. When string is a multiline compound statement, the last character must be '\n'. kind must be 'eval' when string is an expression and the result is meant for eval, otherwise kind must be 'exec'. filename must be a string, and is used only in error messages (if and when errors occur). See also eval in this section and Section 13.1.



Removes attribute name from obj. delattr(obj,'ident') is like del obj.ident. If obj has an attribute named name just because its type or class has it (as is normally the case, for example, with methods of obj), you cannot delete that attribute from obj itself. You may or may not be able to delete that attribute from the type or class itself, depending on what the type or class allows. If you can, obj would cease to have the attribute, and so would every other object of that type or class.



Called without arguments, dir( ) returns the sorted list of all variable names that are bound in the current scope. dir(obj) returns the sorted list of all names of attributes of obj. In Python 2.1 and earlier, dir does not return attributes that obj gets from its type or by inheritance. In Python 2.2 and later, dir returns all attributes, including ones that are inherited and from its type. See also vars in this section.



Divides two numbers and returns a pair whose items are the quotient and remainder. See also _ _divmod_ _ in Chapter 5.



Returns the result of an expression. expr may be a code object ready for evaluation or a string. In the case of a string, eval gets a code object by calling compile(expr, 'string', 'eval'). eval evaluates the code object as an expression, using the globals and locals dictionaries as namespaces. When both arguments are missing, eval uses the current namespace. eval cannot execute statements; it can only evaluate expressions. For more information on eval, see Chapter 13.



execfile is a shortcut for the following statement:

exec open(filename).read(  ) in globals, locals

See Section 13.1.



Constructs a list from those elements of seq for which func is true. func can be any callable object that accepts a single argument or None. seq must be a sequence, iterator, or other iterable object. When func is a callable object, filter calls func on each item of seq and returns the list of items for which func's result is true, like this:

[item for item in seq if func(item)]

When seq is a string or tuple, filter's result is also a string or tuple, rather than a list. When func is None, filter tests for true items like this:

[item for item in seq if item]


Returns obj's attribute named by string name. getattr(obj,'ident') is like obj.ident. When default is present and name is not found in obj, getattr returns default instead of raising AttributeError. See also Section 5.1.4.


globals(  )

Returns the _ _dict_ _ of the calling module (i.e., the dictionary used as the global namespace at the point of call). See also locals in this section.



Returns False if obj has no attribute name (i.e., if getattr(obj,name) raises AttributeError). Otherwise, hasattr returns True. See also Section 5.1.4.



Returns the hash value for obj. obj can be a dictionary key only if obj can be hashed. All numbers that compare equal have the same hash value, even if they are of different types. If the type of obj does not define equality comparison, hash(obj) returns id(obj). See also _ _hash_ _ in Chapter 5.



Converts integer x to a hexadecimal string representation. See also _ _hex_ _ in Chapter 5.



Returns the integer value that denotes the identity of obj. The id of obj is unique and constant during obj's lifetime, but may be reused at any later time after obj is garbage-collected. When a type or class does not define equality comparison, Python uses id to compare and hash instances. For any objects x and y, the identity check x is y has the same result as id(x)= =id(y).



input(prompt) is a shortcut for eval(raw_input(prompt)). In other words, input prompts the user for a line of input, evaluates the resulting string as an expression, and returns the expression's result. The implicit eval may raise SyntaxError or other exceptions. input is therefore rather user-unfriendly and not appropriate for most programs, but it can be handy for experiments and your own test scripts. See also eval and raw_input in this section.



Ensures that string is held in the table of interned strings and returns string itself or a copy. Interned strings compare for equality faster than other strings, but garbage collection cannot recover the memory used for interned strings, so interning too many strings might slow down your program.



Returns True when obj is an instance of class cls (or any subclass of cls) or when cls is a type object and obj is an object of that type. Otherwise it returns False.

Since Python 2.2.1, cls can also be a tuple whose items are classes or types. In this case, isinstance returns True if obj is an instance of any of the items of tuple cls, otherwise isinstance returns False.



Returns True if cls1 is a direct or indirect subclass of cls2, otherwise returns False. cls1 and cls2 must be types or classes.



Creates and returns an iterator: an object with a next method that you can call repeatedly to get one item at a time (see Section in Chapter 4). When called with one argument, iter(obj) normally returns obj._ _iter_ _( ). When obj is a sequence without a special method _ _iter_ _, iter(obj) is equivalent to the following simple generator:

def iterSequence(obj):
    i = 0
    while 1:
        try: yield obj[i]
        except IndexError: raise StopIteration
        i += 1

See also Section 4.10.8 in Chapter 4 and _ _iter_ _ in Chapter 5.

When called with two arguments, the first argument must be callable without arguments, and iter(func,sentinel) is equivalent to the following simple generator:

def iterSentinel(func, sentinel):
    while 1:
        item = func(  )
        if item =  = sentinel: raise StopIteration
        yield item

As discussed in Chapter 4, the statement for x in obj is equivalent to for x in iter(obj). iter is idempotent. In other words, when x is an iterator, iter(x) is x, as long as x supplies an _ _iter_ _ method whose body is just return self, as an iterator should.



Returns the number of items in container, which is a sequence or a mapping. See also _ _len_ _ in Chapter 5.


locals(  )

Returns a dictionary that represents the current local namespace. Treat the returned dictionary as read-only; trying to modify it may or may not affect the values of local variables and might raise an exception. See also globals and vars in this section.



Applies func to every item of seq and returns a list of the results. When map is called with n+1 arguments, the first one, func, can be any callable object that accepts n arguments, or None. The remaining arguments to map must be iterable. When func is callable, map repeatedly calls func with n arguments (one corresponding item from each iterable) and returns the list of results. Thus, map(func, seq) is the same as:

[func(item) for item in seq]

When func is None, map returns a list of tuples, each with n items (one item from each iterable); this is similar to zip, covered in this section. When the iterable objects have different lengths, however, map conceptually pads the shorter ones with None, while zip conceptually truncates the longer ones.



Returns the largest item in the only argument s (s must be iterable) or the largest of multiple arguments.



Returns the smallest item in the only argument s (s must be iterable) or the smallest of multiple arguments.



Converts integer x to an octal string representation. See also _ _oct_ _ in Chapter 5.



Returns the ASCII/ISO integer code between 0 and 255 (inclusive) for the single-character string ch. When ch is Unicode, ord returns an integer code between 0 and 65534 (inclusive). See also chr and unichr in this section.



When z is present, pow(x,y,z) returns x**y%z. When z is missing, pow(x,y) returns x**y. See also _ _pow_ _ in Chapter 5.



Returns a list of integers in arithmetic progression:

[start, start+step, start+2*step, ...]

When start is missing, it defaults to 0. When step is missing, it defaults to 1. When step is 0, range raises ValueError. When step is greater than 0, the last item is the largest start+i*step strictly less than stop. When step is less than 0, the last item is the smallest start+i*step strictly greater than stop. The result is an empty list when start is greater than or equal to stop and step is greater than 0, or when start is less than or equal to stop and step is less than 0. Otherwise, the first item of the result list is always start.



Writes prompt to standard output, reads a line from standard input, and returns the line (without \n) as a string. When at end-of-file, raw_input raises EOFError. See also input in this section.



Applies funct to the items of seq, from left to right, to reduce the sequence to a single value. func must be callable with two arguments. reduce calls func on the first two items of seq, then on the result of the first call and the third item, and so on. reduce returns the result of the last such call. When init is present, it is used before seq's first item, if any. When init is missing, seq must be non-empty. When init is missing and seq has only one item, reduce returns seq[0]. Similarly, when init is present and seq is empty, reduce returns init. The built-in reduce is equivalent to:

def reduce_equivalent(func,seq,init=None):
    if init is None: init, seq = seq[0], seq[1:]
    for item in seq: init = func(init,item)
    return init

A typical use of reduce is to compute the sum of a sequence of numbers:

thesum = reduce(operator.add, seq, 0)


Reloads and reinitializes module object module, and returns module. See Section 7.2.4.



Returns a complete and unambiguous string representation of obj. When feasible, repr returns a string that eval can use to create a new object with the same value as obj. See also str in this section and _ _repr_ _ in Chapter 5.



Returns a float whose value is number x rounded to n digits after the decimal point (i.e., the multiple of 10**-n that is closest to x). When two such multiples are equally close to x, round returns the one that is farther from 0. Since today's computers represent floating-point numbers in binary, not in decimal, most of round's results are not exact.



Binds obj's attribute name to value. setattr(obj,'ident',val) is like obj.ident=val. See also Section 4.3.2 and Section 5.1.4.



Creates and returns a slice object with read-only attributes start, stop, and step bound to the respective argument values, each defaulting to None when missing. Such a slice is meant to signify the same set of indices as range(start,stop,step). Slicing syntax obj[start:stop:step] passes such a slice object as the argument to the _ _getitem_ _, _ _setitem_ _, or _ _delitem_ _ method of object obj, as appropriate. It is up to obj to interpret the slice objects that its methods receive. See also Section



Returns a Unicode string whose single character corresponds to code, where code is an integer between 0 and 65536 (inclusive). See also chr and ord in this section.



When called with no argument, vars( ) returns a dictionary that represents all variables that are bound in the current scope (exactly like locals, covered in this section). This dictionary should be treated as read-only. vars(obj) returns a dictionary that represents all attributes currently bound in obj, as covered in dir in this section. This dictionary may or may not be modifiable, depending on the type of obj.



Returns a sequence object whose items are integers in arithmetic progression. The arguments are the same as for range, covered in this section. While range creates and returns a normal list object, xrange returns a sequence object of a special type, meant only for use in a for statement. xrange consumes less memory than range for this specific, frequent use, although the performance difference is usually small.



Returns a list of tuples, where the nth tuple contains the nth element from each of the argument sequences. zip is called with n iterable objects as arguments (where n is greater than 0). If the iterable objects have different lengths, zip returns a list as long as the shortest iterable, ignoring trailing items in the other iterable objects. See also map in this section.

    Part III: Python Library and Extension Modules