Previous Page
Next Page

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 "Python built-ins" on page 141. Be very careful, however, to avoid accidentally hiding built-ins that your code might need. It's tempting to use, for your own variables, natural names such as file, input, list, filter, but don't do it: these are all names of built-in Python types or functions, and, unless you get into the habit of never shadowing such built-in names with your own, you'll end up with some mysterious bug in your code sooner or later due to such hiding.

Like most built-in functions and types, the functions documented in this section cannot normally be called with named arguments, only with positional ones; in the following, I specifically mention any case in which this limitation does not hold.

_ _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 "Packages" on page 149. 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 "Module Loading" on page 144 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. Should you replace the built-in _ _import_ _ function with your own, in order to provide special import functionality, you may unfortunately have to take parameters globals, locals, and fromlist into account.

abs

abs(x)

Returns the absolute value of number x. When x is complex, abs returns the square root of x.imag**2+x.real**2 (also known as the magnitude of the complex number). Otherwise, abs returns -x if x is less than 0, or x if x is greater than or equal to 0. See also _ _abs_ _, _ _invert_ _, _ _neg_ _, _ _pos_ _ on page 113.

all

all(seq)

seq is any iterable. all returns False if any item of seq is false; otherwise (including the case in which seq is empty), all returns TRue. Python 2.5 only. Like operators and and or, covered in "Short-Circuiting Operators" on page 51, all stops evaluating, and returns a result as soon as the answer is known; in the case of all, this means that evaluation stops as soon as a false item is reached but proceeds throughout seq if all of seq's items are true. Here is a typical toy example of the use of all:

if all(x>0 for x in numbers):
    print "all of the numbers are positive"
else:
    print "some of the numbers are not positive"

any

any(seq)

seq is any iterable. any returns true if any item of seq is true; otherwise (including the case in which seq is empty), any returns False. Python 2.5 only. Like operators and and or, covered in "Short-Circuiting Operators" on page 51, any stops evaluating, and returns a result, as soon as the answer is known; in the case of any, this means that evaluation stops as soon as a true item is reached but proceeds throughout seq if all of seq's items are false. Here is a typical toy example of the use of any:

if any(x<0 for x in numbers):
    print "some of the numbers are negative"
else:
    print "none of the numbers are negative"

callable

callable(obj)

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_ _ on page 105.

chr

chr(code)

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

cmp

cmp(x,y)

Returns 0 when x equals y, -1 when x is less than y, or 1 when x is greater than y. See also _ _cmp_ _ on page 105.

coerce

coerce(x,y)

Returns a pair whose two items are numbers x and y converted to a common type. See "Numeric Conversions" on page 52.

compile

compile(string,filename,kind)

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 on page 161 and "Compile and Code Objects" on page 329.

delattr

delattr(obj,name)

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

dir

dir([obj])

Called without arguments, dir( ) returns a sorted list of all variable names that are bound in the current scope. dir(obj) returns a sorted list of all names of attributes of obj, including ones coming from obj's type or by inheritance. See also vars on page 167.

divmod

divmod(dividend,divisor)

Divides two numbers and returns a pair whose items are the quotient and remainder. See also _ _divmod_ _ on page 114.

eval

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

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. See also "Expressions" on page 329.

execfile

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

execfile is a shortcut for the following statement:

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

See "Dynamic Execution and the exec Statement" on page 328.

filter

filter(func,seq)

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 can be any iterable object. When func is callable, filter calls func on each item of seq and returns the list of items for which func's result is true, just like the following string comprehension:

[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, just like:

[item for item in
seq if item]

getattr

getattr(obj,name[,default])

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 "Attribute Reference Basics" on page 89.

globals

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 on page 164.

hasattr

hasattr(obj,name)

Returns False if obj has no attribute name (i.e., if getattr(obj,name) raises AttributeError). Otherwise, hasattr returns true. See also "Attribute Reference Basics" on page 89.

hash

hash(obj)

Returns the hash value for obj. obj can be a dictionary key, or an item in a set, 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) normally returns id(obj). See also_ _hash_ _ on page 107.

hex

hex(x)

Converts integer x to hexadecimal string representation. See also _ _hex_ _, _ _oct_ _ on page 114.

id

id(obj)

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

input(prompt='')

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 rather user-unfriendly and inappropriate for most programs, but it can be handy for small experiments and your own small exploratory scripts. See also eval on page 161 and raw_input on page 165.

intern

intern(string)

Ensures that string is held in a table of interned strings and returns string itself or a copy. Interned strings may compare for equality slightly faster than other strings because you can use operator is instead of operator == for such comparisons. However, garbage collection can never recover the memory used for interned strings, so interning too many strings might slow down your program by making it take up too much memory. I do not cover the concept of interned strings elsewhere in this book.

isinstance

isinstance(obj,cls)

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

issubclass

issubclass(cls1,cls2)

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

iter

iter(obj)

iter(func,sentinel)

Creates and returns an iterator, which is an object with a next method that you can call repeatedly to get one item at a time (see "Iterators" on page 65). 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 generator:

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

See also "Sequences" on page 40 and _ _iter_ _ on page 112.

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

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

As discussed in "The for Statement" on page 64, the statement for x in obj is exactly equivalent to for x in iter(obj); therefore, do not call iter in such a for statement because it would be redundant, and therefore bad Python style. iter is idempotent. In other words, when x is an iterator, iter(x) is x, as long as x's class supplies an _ _iter_ _ method whose body is just return self, as an iterator's class should.

len

len(container)

Returns the number of items in container, which may be a sequence, a mapping, or a set. See also _ _len_ _ on page 112.

locals

locals( )

Returns a dictionary that represents the current local namespace. Treat the returned dictionary as read-only; trying to modify it may affect the values of local variables and might even raise an exception. See also globals on page 162 and vars on page 167.

map

map(func,seq,*seqs)

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. For example, map(func, seq) is like:

[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." When the iterable objects have different lengths, however, map conceptually pads the shorter ones with None, while zip conceptually truncates the longer ones.

max

max(s,*args)

Returns the largest item in the only argument s (s must then be iterable) or the largest of multiple arguments. In Python 2.5, you can also call max with one positional argument and a named argument key= with the same semantics as for function sorted, covered in sorted on page 167.

min

min(s,*args)

Returns the smallest item in the only argument s (s must then be iterable) or the smallest of multiple arguments. In Python 2.5, you can also call min with one positional argument and a named argument key= with the same semantics as for function sorted, covered in sorted on page 167.

oct

oct(x)

Converts integer x to an octal string representation. See also _ _hex_ _, _ _oct_ _ on page 114.

ord

ord(ch)

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 on page 160 and unichr on page 167.

pow

pow(x,y[,z])

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_ _ on page 115.

range

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

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. See also xrange on page 158.

raw_input

raw_input(prompt='')

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 on page 162.

reduce

reduce(func,seq[,init])

Applies func to the items of seq, from left to right, to reduce the iterable 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 nonempty. 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. reduce is thus roughly equivalent to:

def reduce_equivalent(func,seq,init=None):
    seq = iter(seq)
    if init is None: init =
seq.next( )
    for item in seq:
init = func(init,item)
    return init

An example use of reduce is to compute the product of a sequence of numbers:

thesum = reduce(operator.mul, seq, 1)

reload

reload(module)

Reloads and reinitializes module object module, and returns module. See "The reload Function" on page 146.

repr

repr(obj)

Returns a complete and unambiguous string representation of obj. When feasible, repr returns a string that you can pass to eval in order to create a new object with the same value as obj. See also str on page 273 and _ _repr_ _ on page 108.

round

round(x,n=0)

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. See "The decimal Module" on page 372.

setattr

setattr(obj,name,value)

Binds obj's attribute name to value. setattr(obj,'ident',val) is like obj.ident=val. See also "Object attributes and items" on page 46 and "Setting an attribute" on page 91.

sorted

sorted(seq,cmp=None,key=None,reverse=False)

Returns a list with the same items as iterable seq, in sorted order. Same as:

def sorted(seq,cmp=None,key=None,
reverse=False):
    result = list(seq)
    result.sort(cmp,key,reverse)
    return result

See "Sorting a list" on page 57 for the meaning of the arguments; sorted is one of the few built-in functions that's callable with named arguments. New in Python 2.4.

sum

sum(seq,start=0)

Returns the sum of the items of iterable seq (which should be numbers and, in particular, cannot be strings) plus the value of start. When seq has no items, returns start. To "sum" (concatenate) a sequence of strings, use ''.join(seqofstrs), as covered in join on page 188 and "Building up a string from pieces" on page 484.

unichr

unichr(code)

Returns a Unicode string whose single character corresponds to code, where code is an integer between 0 and 65535 (inclusive). See also str on page 157 and ord on page 165.

vars

vars([obj])

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 "locals"). 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 on page 161. This dictionary may be modifiable, depending on the type of obj.

zip

zip(seq,*seqs)

Returns a list of tuples, where the nth tuple contains the nth element from each of the argument sequences. zip must be called with at least one argument, and all arguments must be iterable. If the iterables have different lengths, zip returns a list as long as the shortest iterable, ignoring trailing items in the other iterable objects. See also map on page 164.



Previous Page
Next Page