blob: ab4b03c98b52da83f8ad15d7b2d519ae8864915d [file] [log] [blame]
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00001\section{Built-in Functions}
2
3The Python interpreter has a number of functions built into it that
4are always available. They are listed here in alphabetical order.
5
6
7\renewcommand{\indexsubitem}{(built-in function)}
8\begin{funcdesc}{abs}{x}
9 Return the absolute value of a number. The argument may be a plain
10 or long integer or a floating point number.
11\end{funcdesc}
12
13\begin{funcdesc}{apply}{function\, args}
14The \var{function} argument must be a callable object (a user-defined or
15built-in function or method, or a class object) and the \var{args}
16argument must be a tuple. The \var{function} is called with
17\var{args} as argument list; the number of arguments is the the length
18of the tuple. (This is different from just calling
19\code{\var{func}(\var{args})}, since in that case there is always
20exactly one argument.)
21\end{funcdesc}
22
23\begin{funcdesc}{chr}{i}
24 Return a string of one character whose \ASCII{} code is the integer
25 \var{i}, e.g., \code{chr(97)} returns the string \code{'a'}. This is the
26 inverse of \code{ord()}. The argument must be in the range [0..255],
27 inclusive.
28\end{funcdesc}
29
30\begin{funcdesc}{cmp}{x\, y}
31 Compare the two objects \var{x} and \var{y} and return an integer
32 according to the outcome. The return value is negative if \code{\var{x}
33 < \var{y}}, zero if \code{\var{x} == \var{y}} and strictly positive if
34 \code{\var{x} > \var{y}}.
35\end{funcdesc}
36
37\begin{funcdesc}{coerce}{x\, y}
38 Return a tuple consisting of the two numeric arguments converted to
39 a common type, using the same rules as used by arithmetic
40 operations.
41\end{funcdesc}
42
43\begin{funcdesc}{compile}{string\, filename\, kind}
44 Compile the \var{string} into a code object. Code objects can be
45 executed by a \code{exec()} statement or evaluated by a call to
46 \code{eval()}. The \var{filename} argument should
47 give the file from which the code was read; pass e.g. \code{'<string>'}
48 if it wasn't read from a file. The \var{kind} argument specifies
49 what kind of code must be compiled; it can be \code{'exec'} if
50 \var{string} consists of a sequence of statements, or \code{'eval'}
51 if it consists of a single expression.
52\end{funcdesc}
53
54\begin{funcdesc}{dir}{}
55 Without arguments, return the list of names in the current local
56 symbol table. With a module, class or class instance object as
57 argument (or anything else that has a \code{__dict__} attribute),
58 returns the list of names in that object's attribute dictionary.
59 The resulting list is sorted. For example:
60
61\bcode\begin{verbatim}
62>>> import sys
63>>> dir()
64['sys']
65>>> dir(sys)
66['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
67>>>
68\end{verbatim}\ecode
69\end{funcdesc}
70
71\begin{funcdesc}{divmod}{a\, b}
72 Take two numbers as arguments and return a pair of integers
73 consisting of their integer quotient and remainder. With mixed
74 operand types, the rules for binary arithmetic operators apply. For
75 plain and long integers, the result is the same as
76 \code{(\var{a} / \var{b}, \var{a} \%{} \var{b})}.
77 For floating point numbers the result is the same as
78 \code{(math.floor(\var{a} / \var{b}), \var{a} \%{} \var{b})}.
79\end{funcdesc}
80
81\begin{funcdesc}{eval}{s\, globals\, locals}
82 The arguments are a string and two optional dictionaries. The
83 string argument is parsed and evaluated as a Python expression
84 (technically speaking, a condition list) using the dictionaries as
85 global and local name space. The string must not contain null bytes
86 or newline characters. The return value is the
87 result of the expression. If the third argument is omitted it
88 defaults to the second. If both dictionaries are omitted, the
89 expression is executed in the environment where \code{eval} is
90 called. Syntax errors are reported as exceptions. Example:
91
92\bcode\begin{verbatim}
93>>> x = 1
94>>> print eval('x+1')
952
96>>>
97\end{verbatim}\ecode
98
99 This function can also be used to execute arbitrary code objects
100 (e.g. created by \code{compile()}). In this case pass a code
101 object instead of a string. The code object must have been compiled
102 passing \code{'eval'} to the \var{kind} argument.
103
104 Note: dynamic execution of statements is supported by the
105 \code{exec} statement.
106
107\end{funcdesc}
108
109\begin{funcdesc}{filter}{function\, list}
110Construct a list from those elements of \var{list} for which
111\var{function} returns true. If \var{list} is a string or a tuple,
112the result also has that type; otherwise it is always a list. If
113\var{function} is \code{None}, the identity function is assumed,
114i.e. all elements of \var{list} that are false (zero or empty) are
115removed.
116\end{funcdesc}
117
118\begin{funcdesc}{float}{x}
119 Convert a number to floating point. The argument may be a plain or
120 long integer or a floating point number.
121\end{funcdesc}
122
123\begin{funcdesc}{getattr}{object\, name}
124 The arguments are an object and a string. The string must be the
125 name
126 of one of the object's attributes. The result is the value of that
127 attribute. For example, \code{getattr(\var{x}, '\var{foobar}')} is equivalent to
128 \code{\var{x}.\var{foobar}}.
129\end{funcdesc}
130
131\begin{funcdesc}{hasattr}{object\, name}
132 The arguments are an object and a string. The result is 1 if the
133 string is the name of one of the object's attributes, 0 if not.
134 (This is implemented by calling \code{getattr(object, name)} and
135 seeing whether it raises an exception or not.)
136\end{funcdesc}
137
138\begin{funcdesc}{hash}{object}
139 Return the hash value of the object (if it has one). Hash values
140 are 32-bit integers. They are used to quickly compare dictionary
141 keys during a dictionary lookup. Numeric values that compare equal
142 have the same hash value (even if they are of different types, e.g.
143 1 and 1.0).
144\end{funcdesc}
145
146\begin{funcdesc}{hex}{x}
147 Convert a number to a hexadecimal string. The result is a valid
148 Python expression.
149\end{funcdesc}
150
151\begin{funcdesc}{id}{object}
152 Return the `identity' of an object. This is an integer which is
153 guaranteed to be unique and constant for this object during its
154 lifetime. (Two objects whose lifetimes are disjunct may have the
155 same id() value.) (Implementation note: this is the address of the
156 object.)
157\end{funcdesc}
158
159\begin{funcdesc}{input}{prompt}
160 Almost equivalent to \code{eval(raw_input(\var{prompt}))}. As for
161 \code{raw_input()}, the prompt argument is optional. The difference is
162 that a long input expression may be broken over multiple lines using the
163 backslash convention.
164\end{funcdesc}
165
166\begin{funcdesc}{int}{x}
167 Convert a number to a plain integer. The argument may be a plain or
168 long integer or a floating point number.
169\end{funcdesc}
170
171\begin{funcdesc}{len}{s}
172 Return the length (the number of items) of an object. The argument
173 may be a sequence (string, tuple or list) or a mapping (dictionary).
174\end{funcdesc}
175
176\begin{funcdesc}{long}{x}
177 Convert a number to a long integer. The argument may be a plain or
178 long integer or a floating point number.
179\end{funcdesc}
180
181\begin{funcdesc}{map}{function\, list\, ...}
182Apply \var{function} to every item of \var{list} and return a list
183of the results. If additional \var{list} arguments are passed,
184\var{function} must take that many arguments and is applied to
185the items of all lists in parallel; if a list is shorter than another
186it is assumed to be extended with \code{None} items. If
187\var{function} is \code{None}, the identity function is assumed; if
188there are multiple list arguments, \code{map} returns a list
189consisting of tuples containing the corresponding items from all lists
190(i.e. a kind of transpose operation). The \var{list} arguments may be
191any kind of sequence; the result is always a list.
192\end{funcdesc}
193
194\begin{funcdesc}{max}{s}
195 Return the largest item of a non-empty sequence (string, tuple or
196 list).
197\end{funcdesc}
198
199\begin{funcdesc}{min}{s}
200 Return the smallest item of a non-empty sequence (string, tuple or
201 list).
202\end{funcdesc}
203
204\begin{funcdesc}{oct}{x}
205 Convert a number to an octal string. The result is a valid Python
206 expression.
207\end{funcdesc}
208
209\begin{funcdesc}{open}{filename\, mode}
210 % XXXJH xrefs here to Built-in types?
211 Return a new file object (described earlier under Built-in Types).
212 The string arguments are the same as for \code{stdio}'s
213 \code{fopen()}: \var{filename} is the file name to be opened,
214 \var{mode} indicates how the file is to be opened: \code{'r'} for
215 reading, \code{'w'} for writing (truncating an existing file), and
216 \code{'a'} opens it for appending. Modes \code{'r+'}, \code{'w+'} and
217 \code{'a+'} open the file for updating, provided the underlying
218 \code{stdio} library understands this. On systems that differentiate
219 between binary and text files, \code{'b'} appended to the mode opens
220 the file in binary mode. If the file cannot be opened, \code{IOError}
221 is raised.
222\end{funcdesc}
223
224\begin{funcdesc}{ord}{c}
225 Return the \ASCII{} value of a string of one character. E.g.,
226 \code{ord('a')} returns the integer \code{97}. This is the inverse of
227 \code{chr()}.
228\end{funcdesc}
229
230\begin{funcdesc}{pow}{x\, y}
231 Return \var{x} to the power \var{y}. The arguments must have
232 numeric types. With mixed operand types, the rules for binary
233 arithmetic operators apply. The effective operand type is also the
234 type of the result; if the result is not expressible in this type, the
235 function raises an exception; e.g., \code{pow(2, -1)} is not allowed.
236\end{funcdesc}
237
238\begin{funcdesc}{range}{start\, end\, step}
239 This is a versatile function to create lists containing arithmetic
240 progressions. It is most often used in \code{for} loops. The
241 arguments must be plain integers. If the \var{step} argument is
242 omitted, it defaults to \code{1}. If the \var{start} argument is
243 omitted, it defaults to \code{0}. The full form returns a list of
244 plain integers \code{[\var{start}, \var{start} + \var{step},
245 \var{start} + 2 * \var{step}, \ldots]}. If \var{step} is positive,
246 the last element is the largest \code{\var{start} + \var{i} *
247 \var{step}} less than \var{end}; if \var{step} is negative, the last
248 element is the largest \code{\var{start} + \var{i} * \var{step}}
249 greater than \var{end}. \var{step} must not be zero. Example:
250
251\bcode\begin{verbatim}
252>>> range(10)
253[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
254>>> range(1, 11)
255[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
256>>> range(0, 30, 5)
257[0, 5, 10, 15, 20, 25]
258>>> range(0, 10, 3)
259[0, 3, 6, 9]
260>>> range(0, -10, -1)
261[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
262>>> range(0)
263[]
264>>> range(1, 0)
265[]
266>>>
267\end{verbatim}\ecode
268\end{funcdesc}
269
270\begin{funcdesc}{raw_input}{prompt}
271 The string argument is optional; if present, it is written to
272 standard
273 output without a trailing newline. The function then reads a line
274 from input, converts it to a string (stripping a trailing newline),
275 and returns that. When \EOF{} is read, \code{EOFError} is raised.
276 Example:
277
278\bcode\begin{verbatim}
279>>> s = raw_input('--> ')
280--> Monty Python's Flying Circus
281>>> s
282'Monty Python\'s Flying Circus'
283>>>
284\end{verbatim}\ecode
285\end{funcdesc}
286
287\begin{funcdesc}{reduce}{function\, list\, initializer}
288Apply the binary \var{function} to the items of \var{list} so as to
289reduce the list to a single value. E.g.,
290\code{reduce(lambda x, y: x*y, \var{list}, 1)} returns the product of
291the elements of \var{list}. The optional \var{initializer} can be
292thought of as being prepended to \var{list} so as to allow reduction
293of an empty \var{list}. The \var{list} arguments may be any kind of
294sequence.
295\end{funcdesc}
296
297\begin{funcdesc}{reload}{module}
298 Re-parse and re-initialize an already imported \var{module}. The
299 argument must be a module object, so it must have been successfully
300 imported before. This is useful if you have edited the module source
301 file using an external editor and want to try out the new version
302 without leaving the Python interpreter. Note that if a module is
303 syntactically correct but its initialization fails, the first
304 \code{import} statement for it does not import the name, but does
305 create a (partially initialized) module object; to reload the module
306 you must first \code{import} it again (this will just make the
307 partially initialized module object available) before you can
308 \code{reload()} it.
309\end{funcdesc}
310
311\begin{funcdesc}{repr}{object}
312Return a string containing a printable representation of an object.
313This is the same value yielded by conversions (reverse quotes).
314It is sometimes useful to be able to access this operation as an
315ordinary function. For many types, this function makes an attempt
316to return a string that would yield an object with the same value
317when passed to \code{eval()}.
318\end{funcdesc}
319
320\begin{funcdesc}{round}{x\, n}
321 Return the floating point value \var{x} rounded to \var{n} digits
322 after the decimal point. If \var{n} is omitted, it defaults to zero.
323 The result is a floating point number. Values are rounded to the
324 closest multiple of 10 to the power minus \var{n}; if two multiples
325 are equally close, rounding is done away from 0 (so e.g.
326 \code{round(0.5)} is \code{1.0} and \code{round(-0.5)} is \code{-1.0}).
327\end{funcdesc}
328
329\begin{funcdesc}{setattr}{object\, name\, value}
330 This is the counterpart of \code{getattr}. The arguments are an
331 object, a string and an arbitrary value. The string must be the name
332 of one of the object's attributes. The function assigns the value to
333 the attribute, provided the object allows it. For example,
334 \code{setattr(\var{x}, '\var{foobar}', 123)} is equivalent to
335 \code{\var{x}.\var{foobar} = 123}.
336\end{funcdesc}
337
338\begin{funcdesc}{str}{object}
339Return a string containing a nicely printable representation of an
340object. For strings, this returns the string itself. The difference
341with \code{repr(\var{object}} is that \code{str(\var{object}} does not
342always attempt to return a string that is acceptable to \code{eval()};
343its goal is to return a printable string.
344\end{funcdesc}
345
346\begin{funcdesc}{type}{object}
347% XXXJH xref to buil-in objects here?
348 Return the type of an \var{object}. The return value is a type
349 object. There is not much you can do with type objects except compare
350 them to other type objects; e.g., the following checks if a variable
351 is a string:
352
353\bcode\begin{verbatim}
354>>> if type(x) == type(''): print 'It is a string'
355\end{verbatim}\ecode
356\end{funcdesc}
Guido van Rossum68cfbe71994-02-24 11:28:27 +0000357
Guido van Rossum17383111994-04-21 10:32:28 +0000358\begin{funcdesc}{vars}{}
359Without arguments, return a dictionary corresponding to the current
360local symbol table. With a module, class or class instance object as
361argument (or anything else that has a \code{__dict__} attribute),
362returns a dictionary corresponding to the object's symbol table.
363The returned dictionary should not be modified: the effects on the
364corresponding symbol table are undefined.%
365\footnote{In the current implementation, local variable bindings
366cannot normally be affected this way, but variables retrieved from
367other scopes can be. This may change.}
368\end{funcdesc}
369
Guido van Rossum68cfbe71994-02-24 11:28:27 +0000370\begin{funcdesc}{xrange}{start\, end\, step}
371This function is very similar to \code{range()}, but returns an
372``xrange object'' instead of a list. This is an opaque sequence type
373which yields the same values as the corresponding list, without
374actually storing them all simultaneously. The advantage of
375\code{xrange()} over \code{range()} is minimal (since \code{xrange()}
376still has to create the values when asked for them) except when a very
377large range is used on a memory-starved machine (e.g. DOS) or when all
378of the range's elements are never used (e.g. when the loop is usually
379terminated with \code{break}).
380\end{funcdesc}