1 \section{Built-in Functions
\label{built-in-funcs
}}
3 The Python interpreter has a number of functions built into it that
4 are always available. They are listed here in alphabetical order.
7 \setindexsubitem{(built-in function)
}
9 \begin{funcdesc
}{__import__
}{name
\optional{, globals
\optional{, locals
\optional{, fromlist
}}}}
10 This function is invoked by the
\keyword{import
}\stindex{import
}
11 statement. It mainly exists so that you can replace it with another
12 function that has a compatible interface, in order to change the
13 semantics of the
\keyword{import
} statement. For examples of why
14 and how you would do this, see the standard library modules
15 \module{ihooks
}\refstmodindex{ihooks
} and
16 \refmodule{rexec
}\refstmodindex{rexec
}. See also the built-in
17 module
\refmodule{imp
}\refbimodindex{imp
}, which defines some useful
18 operations out of which you can build your own
19 \function{__import__()
} function.
21 For example, the statement
\samp{import spam
} results in the
22 following call:
\code{__import__('spam',
} \code{globals(),
}
23 \code{locals(),
[])
}; the statement
\samp{from spam.ham import eggs
}
24 results in
\samp{__import__('spam.ham', globals(), locals(),
25 ['eggs'
])
}. Note that even though
\code{locals()
} and
26 \code{['eggs'
]} are passed in as arguments, the
27 \function{__import__()
} function does not set the local variable
28 named
\code{eggs
}; this is done by subsequent code that is generated
29 for the import statement. (In fact, the standard implementation
30 does not use its
\var{locals
} argument at all, and uses its
31 \var{globals
} only to determine the package context of the
32 \keyword{import
} statement.)
34 When the
\var{name
} variable is of the form
\code{package.module
},
35 normally, the top-level package (the name up till the first dot) is
36 returned,
\emph{not
} the module named by
\var{name
}. However, when
37 a non-empty
\var{fromlist
} argument is given, the module named by
38 \var{name
} is returned. This is done for compatibility with the
39 bytecode generated for the different kinds of import statement; when
40 using
\samp{import spam.ham.eggs
}, the top-level package
\module{spam
}
41 must be placed in the importing namespace, but when using
\samp{from
42 spam.ham import eggs
}, the
\code{spam.ham
} subpackage must be used
43 to find the
\code{eggs
} variable. As a workaround for this
44 behavior, use
\function{getattr()
} to extract the desired
45 components. For example, you could define the following helper:
49 mod = __import__(name)
50 components = name.split('.')
51 for comp in components
[1:
]:
52 mod = getattr(mod, comp)
57 \begin{funcdesc
}{abs
}{x
}
58 Return the absolute value of a number. The argument may be a plain
59 or long integer or a floating point number. If the argument is a
60 complex number, its magnitude is returned.
63 \begin{funcdesc
}{basestring
}{}
64 This abstract type is the superclass for
\class{str
} and
\class{unicode
}.
65 It cannot be called or instantiated, but it can be used to test whether
66 an object is an instance of
\class{str
} or
\class{unicode
}.
67 \code{isinstance(obj, basestring)
} is equivalent to
68 \code{isinstance(obj, (str, unicode))
}.
72 \begin{funcdesc
}{bool
}{\optional{x
}}
73 Convert a value to a Boolean, using the standard truth testing
74 procedure. If
\var{x
} is false or omitted, this returns
75 \constant{False
}; otherwise it returns
\constant{True
}.
76 \class{bool
} is also a class, which is a subclass of
\class{int
}.
77 Class
\class{bool
} cannot be subclassed further. Its only instances
78 are
\constant{False
} and
\constant{True
}.
80 \indexii{Boolean
}{type
}
82 \versionchanged[If no argument is given, this function returns
83 \constant{False
}]{2.3}
86 \begin{funcdesc
}{callable
}{object
}
87 Return true if the
\var{object
} argument appears callable, false if
88 not. If this returns true, it is still possible that a call fails,
89 but if it is false, calling
\var{object
} will never succeed. Note
90 that classes are callable (calling a class returns a new instance);
91 class instances are callable if they have a
\method{__call__()
}
95 \begin{funcdesc
}{chr
}{i
}
96 Return a string of one character whose
\ASCII{} code is the integer
97 \var{i
}. For example,
\code{chr(
97)
} returns the string
\code{'a'
}.
98 This is the inverse of
\function{ord()
}. The argument must be in
99 the range
[0.
.255], inclusive;
\exception{ValueError
} will be raised
100 if
\var{i
} is outside that range.
103 \begin{funcdesc
}{classmethod
}{function
}
104 Return a class method for
\var{function
}.
106 A class method receives the class as implicit first argument,
107 just like an instance method receives the instance.
108 To declare a class method, use this idiom:
112 def f(cls, arg1, arg2, ...): ...
116 It can be called either on the class (such as
\code{C.f()
}) or on an
117 instance (such as
\code{C().f()
}). The instance is ignored except for
119 If a class method is called for a derived class, the derived class
120 object is passed as the implied first argument.
122 Class methods are different than
\Cpp{} or Java static methods.
123 If you want those, see
\function{staticmethod()
} in this section.
127 \begin{funcdesc
}{cmp
}{x, y
}
128 Compare the two objects
\var{x
} and
\var{y
} and return an integer
129 according to the outcome. The return value is negative if
\code{\var{x
}
130 <
\var{y
}}, zero if
\code{\var{x
} ==
\var{y
}} and strictly positive if
131 \code{\var{x
} >
\var{y
}}.
134 \begin{funcdesc
}{compile
}{string, filename, kind
\optional{,
135 flags
\optional{, dont_inherit
}}}
136 Compile the
\var{string
} into a code object. Code objects can be
137 executed by an
\keyword{exec
} statement or evaluated by a call to
138 \function{eval()
}. The
\var{filename
} argument should
139 give the file from which the code was read; pass some recognizable value
140 if it wasn't read from a file (
\code{'<string>'
} is commonly used).
141 The
\var{kind
} argument specifies what kind of code must be
142 compiled; it can be
\code{'exec'
} if
\var{string
} consists of a
143 sequence of statements,
\code{'eval'
} if it consists of a single
144 expression, or
\code{'single'
} if it consists of a single
145 interactive statement (in the latter case, expression statements
146 that evaluate to something else than
\code{None
} will printed).
148 When compiling multi-line statements, two caveats apply: line
149 endings must be represented by a single newline character
150 (
\code{'
\e n'
}), and the input must be terminated by at least one
151 newline character. If line endings are represented by
152 \code{'
\e r
\e n'
}, use the string
\method{replace()
} method to
153 change them into
\code{'
\e n'
}.
155 The optional arguments
\var{flags
} and
\var{dont_inherit
}
156 (which are new in Python
2.2) control which future statements (see
157 \pep{236}) affect the compilation of
\var{string
}. If neither is
158 present (or both are zero) the code is compiled with those future
159 statements that are in effect in the code that is calling compile.
160 If the
\var{flags
} argument is given and
\var{dont_inherit
} is not
161 (or is zero) then the future statements specified by the
\var{flags
}
162 argument are used in addition to those that would be used anyway.
163 If
\var{dont_inherit
} is a non-zero integer then the
\var{flags
}
164 argument is it -- the future statements in effect around the call to
167 Future statemants are specified by bits which can be bitwise or-ed
168 together to specify multiple statements. The bitfield required to
169 specify a given feature can be found as the
\member{compiler_flag
}
170 attribute on the
\class{_Feature
} instance in the
171 \module{__future__
} module.
174 \begin{funcdesc
}{complex
}{\optional{real
\optional{, imag
}}}
175 Create a complex number with the value
\var{real
} +
\var{imag
}*j or
176 convert a string or number to a complex number. If the first
177 parameter is a string, it will be interpreted as a complex number
178 and the function must be called without a second parameter. The
179 second parameter can never be a string.
180 Each argument may be any numeric type (including complex).
181 If
\var{imag
} is omitted, it defaults to zero and the function
182 serves as a numeric conversion function like
\function{int()
},
183 \function{long()
} and
\function{float()
}. If both arguments
184 are omitted, returns
\code{0j
}.
187 \begin{funcdesc
}{delattr
}{object, name
}
188 This is a relative of
\function{setattr()
}. The arguments are an
189 object and a string. The string must be the name
190 of one of the object's attributes. The function deletes
191 the named attribute, provided the object allows it. For example,
192 \code{delattr(
\var{x
}, '
\var{foobar
}')
} is equivalent to
193 \code{del
\var{x
}.
\var{foobar
}}.
196 \begin{funcdesc
}{dict
}{\optional{mapping-or-sequence
}}
197 Return a new dictionary initialized from an optional positional
198 argument or from a set of keyword arguments.
199 If no arguments are given, return a new empty dictionary.
200 If the positional argument is a mapping object, return a dictionary
201 mapping the same keys to the same values as does the mapping object.
202 Otherwise the positional argument must be a sequence, a container that
203 supports iteration, or an iterator object. The elements of the argument
204 must each also be of one of those kinds, and each must in turn contain
205 exactly two objects. The first is used as a key in the new dictionary,
206 and the second as the key's value. If a given key is seen more than
207 once, the last value associated with it is retained in the new
210 If keyword arguments are given, the keywords themselves with their
211 associated values are added as items to the dictionary. If a key
212 is specified both in the positional argument and as a keyword argument,
213 the value associated with the keyword is retained in the dictionary.
214 For example, these all return a dictionary equal to
215 \code{\
{"one":
2, "two":
3\
}}:
218 \item \code{dict(\
{'one':
2, 'two':
3\
})
}
219 \item \code{dict(\
{'one':
2, 'two':
3\
}.items())
}
220 \item \code{dict(\
{'one':
2, 'two':
3\
}.iteritems())
}
221 \item \code{dict(zip(('one', 'two'), (
2,
3)))
}
222 \item \code{dict(
[['two',
3],
['one',
2]])
}
223 \item \code{dict(one=
2, two=
3)
}
224 \item \code{dict(
[(
['one', 'two'
][i-
2], i) for i in (
2,
3)
])
}
228 \versionchanged[Support for building a dictionary from keyword
229 arguments added
]{2.3}
232 \begin{funcdesc
}{dir
}{\optional{object
}}
233 Without arguments, return the list of names in the current local
234 symbol table. With an argument, attempts to return a list of valid
235 attributes for that object. This information is gleaned from the
236 object's
\member{__dict__
} attribute, if defined, and from the class
237 or type object. The list is not necessarily complete.
238 If the object is a module object, the list contains the names of the
240 If the object is a type or class object,
241 the list contains the names of its attributes,
242 and recursively of the attributes of its bases.
243 Otherwise, the list contains the object's attributes' names,
244 the names of its class's attributes,
245 and recursively of the attributes of its class's base classes.
246 The resulting list is sorted alphabetically.
252 ['__builtins__', '__doc__', '__name__', 'struct'
]
254 ['__doc__', '__name__', 'calcsize', 'error', 'pack', 'unpack'
]
257 \note{Because
\function{dir()
} is supplied primarily as a convenience
258 for use at an interactive prompt,
259 it tries to supply an interesting set of names more than it tries to
260 supply a rigorously or consistently defined set of names,
261 and its detailed behavior may change across releases.
}
264 \begin{funcdesc
}{divmod
}{a, b
}
265 Take two (non complex) numbers as arguments and return a pair of numbers
266 consisting of their quotient and remainder when using long division. With
267 mixed operand types, the rules for binary arithmetic operators apply. For
268 plain and long integers, the result is the same as
269 \code{(
\var{a
} /
\var{b
},
\var{a
} \%
{} \var{b
})
}.
270 For floating point numbers the result is
\code{(
\var{q
},
\var{a
} \%
{}
271 \var{b
})
}, where
\var{q
} is usually
\code{math.floor(
\var{a
} /
272 \var{b
})
} but may be
1 less than that. In any case
\code{\var{q
} *
273 \var{b
} +
\var{a
} \%
{} \var{b
}} is very close to
\var{a
}, if
274 \code{\var{a
} \%
{} \var{b
}} is non-zero it has the same sign as
275 \var{b
}, and
\code{0 <= abs(
\var{a
} \%
{} \var{b
}) < abs(
\var{b
})
}.
277 \versionchanged[Using
\function{divmod()
} with complex numbers is
281 \begin{funcdesc
}{enumerate
}{iterable
}
282 Return an enumerate object.
\var{iterable
} must be a sequence, an
283 iterator, or some other object which supports iteration. The
284 \method{next()
} method of the iterator returned by
285 \function{enumerate()
} returns a tuple containing a count (from
286 zero) and the corresponding value obtained from iterating over
287 \var{iterable
}.
\function{enumerate()
} is useful for obtaining an
288 indexed series:
\code{(
0, seq
[0])
},
\code{(
1, seq
[1])
},
\code{(
2,
293 \begin{funcdesc
}{eval
}{expression
\optional{, globals
\optional{, locals
}}}
294 The arguments are a string and two optional dictionaries. The
295 \var{expression
} argument is parsed and evaluated as a Python
296 expression (technically speaking, a condition list) using the
297 \var{globals
} and
\var{locals
} dictionaries as global and local name
298 space. If the
\var{globals
} dictionary is present and lacks
299 '__builtins__', the current globals are copied into
\var{globals
} before
300 \var{expression
} is parsed. This means that
\var{expression
}
301 normally has full access to the standard
302 \refmodule[builtin
]{__builtin__
} module and restricted environments
303 are propagated. If the
\var{locals
} dictionary is omitted it defaults to
304 the
\var{globals
} dictionary. If both dictionaries are omitted, the
305 expression is executed in the environment where
\keyword{eval
} is
306 called. The return value is the result of the evaluated expression.
307 Syntax errors are reported as exceptions. Example:
311 >>> print eval('x+
1')
315 This function can also be used to execute arbitrary code objects
316 (such as those created by
\function{compile()
}). In this case pass
317 a code object instead of a string. The code object must have been
318 compiled passing
\code{'eval'
} as the
\var{kind
} argument.
320 Hints: dynamic execution of statements is supported by the
321 \keyword{exec
} statement. Execution of statements from a file is
322 supported by the
\function{execfile()
} function. The
323 \function{globals()
} and
\function{locals()
} functions returns the
324 current global and local dictionary, respectively, which may be
325 useful to pass around for use by
\function{eval()
} or
326 \function{execfile()
}.
329 \begin{funcdesc
}{execfile
}{filename
\optional{, globals
\optional{, locals
}}}
330 This function is similar to the
331 \keyword{exec
} statement, but parses a file instead of a string. It
332 is different from the
\keyword{import
} statement in that it does not
333 use the module administration --- it reads the file unconditionally
334 and does not create a new module.
\footnote{It is used relatively
335 rarely so does not warrant being made into a statement.
}
337 The arguments are a file name and two optional dictionaries. The
338 file is parsed and evaluated as a sequence of Python statements
339 (similarly to a module) using the
\var{globals
} and
\var{locals
}
340 dictionaries as global and local namespace. If the
\var{locals
}
341 dictionary is omitted it defaults to the
\var{globals
} dictionary.
342 If both dictionaries are omitted, the expression is executed in the
343 environment where
\function{execfile()
} is called. The return value is
346 \warning{The default
\var{locals
} act as described for function
347 \function{locals()
} below: modifications to the default
\var{locals
}
348 dictionary should not be attempted. Pass an explicit
\var{locals
}
349 dictionary if you need to see effects of the code on
\var{locals
} after
350 function
\function{execfile()
} returns.
\function{execfile()
} cannot
351 be used reliably to modify a function's locals.
}
354 \begin{funcdesc
}{file
}{filename
\optional{, mode
\optional{, bufsize
}}}
355 Return a new file object (described in
356 section~
\ref{bltin-file-objects
}, ``
\ulink{File
357 Objects
}{bltin-file-objects.html
}'').
358 The first two arguments are the same as for
\code{stdio
}'s
359 \cfunction{fopen()
}:
\var{filename
} is the file name to be opened,
360 \var{mode
} indicates how the file is to be opened:
\code{'r'
} for
361 reading,
\code{'w'
} for writing (truncating an existing file), and
362 \code{'a'
} opens it for appending (which on
\emph{some
} \UNIX{}
363 systems means that
\emph{all
} writes append to the end of the file,
364 regardless of the current seek position).
366 Modes
\code{'r+'
},
\code{'w+'
} and
\code{'a+'
} open the file for
367 updating (note that
\code{'w+'
} truncates the file). Append
368 \code{'b'
} to the mode to open the file in binary mode, on systems
369 that differentiate between binary and text files (else it is
370 ignored). If the file cannot be opened,
\exception{IOError
} is
373 In addition to the standard
\cfunction{fopen()
} values
\var{mode
}
374 may be
\code{'U'
} or
\code{'rU'
}. If Python is built with universal
375 newline support (the default) the file is opened as a text file, but
376 lines may be terminated by any of
\code{'
\e n'
}, the Unix end-of-line
378 \code{'
\e r'
}, the Macintosh convention or
\code{'
\e r
\e n'
}, the Windows
379 convention. All of these external representations are seen as
381 by the Python program. If Python is built without universal newline support
382 \var{mode
} \code{'U'
} is the same as normal text mode. Note that
383 file objects so opened also have an attribute called
384 \member{newlines
} which has a value of
\code{None
} (if no newlines
385 have yet been seen),
\code{'
\e n'
},
\code{'
\e r'
},
\code{'
\e r
\e n'
},
386 or a tuple containing all the newline types seen.
388 If
\var{mode
} is omitted, it defaults to
\code{'r'
}. When opening a
389 binary file, you should append
\code{'b'
} to the
\var{mode
} value
390 for improved portability. (It's useful even on systems which don't
391 treat binary and text files differently, where it serves as
393 \index{line-buffered I/O
}\index{unbuffered I/O
}\index{buffer size, I/O
}
394 \index{I/O control!buffering
}
395 The optional
\var{bufsize
} argument specifies the
396 file's desired buffer size:
0 means unbuffered,
1 means line
397 buffered, any other positive value means use a buffer of
398 (approximately) that size. A negative
\var{bufsize
} means to use
399 the system default, which is usually line buffered for tty
400 devices and fully buffered for other files. If omitted, the system
401 default is used.
\footnote{
402 Specifying a buffer size currently has no effect on systems that
403 don't have
\cfunction{setvbuf()
}. The interface to specify the
404 buffer size is not done using a method that calls
405 \cfunction{setvbuf()
}, because that may dump core when called
406 after any I/O has been performed, and there's no reliable way to
407 determine whether this is the case.
}
409 The
\function{file()
} constructor is new in Python
2.2. The previous
410 spelling,
\function{open()
}, is retained for compatibility, and is an
411 alias for
\function{file()
}.
414 \begin{funcdesc
}{filter
}{function, list
}
415 Construct a list from those elements of
\var{list
} for which
416 \var{function
} returns true.
\var{list
} may be either a sequence, a
417 container which supports iteration, or an iterator, If
\var{list
}
418 is a string or a tuple, the result also has that type; otherwise it
419 is always a list. If
\var{function
} is
\code{None
}, the identity
420 function is assumed, that is, all elements of
\var{list
} that are false
421 (zero or empty) are removed.
423 Note that
\code{filter(function,
\var{list
})
} is equivalent to
424 \code{[item for item in
\var{list
} if function(item)
]} if function is
425 not
\code{None
} and
\code{[item for item in
\var{list
} if item
]} if
426 function is
\code{None
}.
429 \begin{funcdesc
}{float
}{\optional{x
}}
430 Convert a string or a number to floating point. If the argument is a
431 string, it must contain a possibly signed decimal or floating point
432 number, possibly embedded in whitespace; this behaves identical to
433 \code{string.atof(
\var{x
})
}. Otherwise, the argument may be a plain
434 or long integer or a floating point number, and a floating point
435 number with the same value (within Python's floating point
436 precision) is returned. If no argument is given, returns
\code{0.0}.
438 \note{When passing in a string, values for NaN
\index{NaN
}
439 and Infinity
\index{Infinity
} may be returned, depending on the
440 underlying C library. The specific set of strings accepted which
441 cause these values to be returned depends entirely on the C library
442 and is known to vary.
}
445 \begin{funcdesc
}{getattr
}{object, name
\optional{, default
}}
446 Return the value of the named attributed of
\var{object
}.
\var{name
}
447 must be a string. If the string is the name of one of the object's
448 attributes, the result is the value of that attribute. For example,
449 \code{getattr(x, 'foobar')
} is equivalent to
\code{x.foobar
}. If the
450 named attribute does not exist,
\var{default
} is returned if provided,
451 otherwise
\exception{AttributeError
} is raised.
454 \begin{funcdesc
}{globals
}{}
455 Return a dictionary representing the current global symbol table.
456 This is always the dictionary of the current module (inside a
457 function or method, this is the module where it is defined, not the
458 module from which it is called).
461 \begin{funcdesc
}{hasattr
}{object, name
}
462 The arguments are an object and a string. The result is
\code{True
} if the
463 string is the name of one of the object's attributes,
\code{False
} if not.
464 (This is implemented by calling
\code{getattr(
\var{object
},
465 \var{name
})
} and seeing whether it raises an exception or not.)
468 \begin{funcdesc
}{hash
}{object
}
469 Return the hash value of the object (if it has one). Hash values
470 are integers. They are used to quickly compare dictionary
471 keys during a dictionary lookup. Numeric values that compare equal
472 have the same hash value (even if they are of different types, as is
473 the case for
1 and
1.0).
476 \begin{funcdesc
}{help
}{\optional{object
}}
477 Invoke the built-in help system. (This function is intended for
478 interactive use.) If no argument is given, the interactive help
479 system starts on the interpreter console. If the argument is a
480 string, then the string is looked up as the name of a module,
481 function, class, method, keyword, or documentation topic, and a
482 help page is printed on the console. If the argument is any other
483 kind of object, a help page on the object is generated.
487 \begin{funcdesc
}{hex
}{x
}
488 Convert an integer number (of any size) to a hexadecimal string.
489 The result is a valid Python expression. Note: this always yields
490 an unsigned literal. For example, on a
32-bit machine,
491 \code{hex(-
1)
} yields
\code{'
0xffffffff'
}. When evaluated on a
492 machine with the same word size, this literal is evaluated as -
1; at
493 a different word size, it may turn up as a large positive number or
494 raise an
\exception{OverflowError
} exception.
497 \begin{funcdesc
}{id
}{object
}
498 Return the `identity' of an object. This is an integer (or long
499 integer) which is guaranteed to be unique and constant for this
500 object during its lifetime. Two objects whose lifetimes are
501 disjunct may have the same
\function{id()
} value. (Implementation
502 note: this is the address of the object.)
505 \begin{funcdesc
}{input
}{\optional{prompt
}}
506 Equivalent to
\code{eval(raw_input(
\var{prompt
}))
}.
507 \warning{This function is not safe from user errors! It
508 expects a valid Python expression as input; if the input is not
509 syntactically valid, a
\exception{SyntaxError
} will be raised.
510 Other exceptions may be raised if there is an error during
511 evaluation. (On the other hand, sometimes this is exactly what you
512 need when writing a quick script for expert use.)
}
514 If the
\refmodule{readline
} module was loaded, then
515 \function{input()
} will use it to provide elaborate line editing and
518 Consider using the
\function{raw_input()
} function for general input
522 \begin{funcdesc
}{int
}{\optional{x
\optional{, radix
}}}
523 Convert a string or number to a plain integer. If the argument is a
524 string, it must contain a possibly signed decimal number
525 representable as a Python integer, possibly embedded in whitespace.
526 The
\var{radix
} parameter gives the base for the
527 conversion and may be any integer in the range
[2,
36], or zero. If
528 \var{radix
} is zero, the proper radix is guessed based on the
529 contents of string; the interpretation is the same as for integer
530 literals. If
\var{radix
} is specified and
\var{x
} is not a string,
531 \exception{TypeError
} is raised.
532 Otherwise, the argument may be a plain or
533 long integer or a floating point number. Conversion of floating
534 point numbers to integers truncates (towards zero).
535 If the argument is outside the integer range a long object will
536 be returned instead. If no arguments are given, returns
\code{0}.
539 \begin{funcdesc
}{isinstance
}{object, classinfo
}
540 Return true if the
\var{object
} argument is an instance of the
541 \var{classinfo
} argument, or of a (direct or indirect) subclass
542 thereof. Also return true if
\var{classinfo
} is a type object and
543 \var{object
} is an object of that type. If
\var{object
} is not a
544 class instance or an object of the given type, the function always
545 returns false. If
\var{classinfo
} is neither a class object nor a
546 type object, it may be a tuple of class or type objects, or may
547 recursively contain other such tuples (other sequence types are not
548 accepted). If
\var{classinfo
} is not a class, type, or tuple of
549 classes, types, and such tuples, a
\exception{TypeError
} exception
551 \versionchanged[Support for a tuple of type information was added
]{2.2}
554 \begin{funcdesc
}{issubclass
}{class, classinfo
}
555 Return true if
\var{class
} is a subclass (direct or indirect) of
556 \var{classinfo
}. A class is considered a subclass of itself.
557 \var{classinfo
} may be a tuple of class objects, in which case every
558 entry in
\var{classinfo
} will be checked. In any other case, a
559 \exception{TypeError
} exception is raised.
560 \versionchanged[Support for a tuple of type information was added
]{2.3}
563 \begin{funcdesc
}{iter
}{o
\optional{, sentinel
}}
564 Return an iterator object. The first argument is interpreted very
565 differently depending on the presence of the second argument.
566 Without a second argument,
\var{o
} must be a collection object which
567 supports the iteration protocol (the
\method{__iter__()
} method), or
568 it must support the sequence protocol (the
\method{__getitem__()
}
569 method with integer arguments starting at
\code{0}). If it does not
570 support either of those protocols,
\exception{TypeError
} is raised.
571 If the second argument,
\var{sentinel
}, is given, then
\var{o
} must
572 be a callable object. The iterator created in this case will call
573 \var{o
} with no arguments for each call to its
\method{next()
}
574 method; if the value returned is equal to
\var{sentinel
},
575 \exception{StopIteration
} will be raised, otherwise the value will
580 \begin{funcdesc
}{len
}{s
}
581 Return the length (the number of items) of an object. The argument
582 may be a sequence (string, tuple or list) or a mapping (dictionary).
585 \begin{funcdesc
}{list
}{\optional{sequence
}}
586 Return a list whose items are the same and in the same order as
587 \var{sequence
}'s items.
\var{sequence
} may be either a sequence, a
588 container that supports iteration, or an iterator object. If
589 \var{sequence
} is already a list, a copy is made and returned,
590 similar to
\code{\var{sequence
}[:
]}. For instance,
591 \code{list('abc')
} returns
\code{['a', 'b', 'c'
]} and
\code{list(
592 (
1,
2,
3) )
} returns
\code{[1,
2,
3]}. If no argument is given,
593 returns a new empty list,
\code{[]}.
596 \begin{funcdesc
}{locals
}{}
597 Update and return a dictionary representing the current local symbol table.
598 \warning{The contents of this dictionary should not be modified;
599 changes may not affect the values of local variables used by the
603 \begin{funcdesc
}{long
}{\optional{x
\optional{, radix
}}}
604 Convert a string or number to a long integer. If the argument is a
605 string, it must contain a possibly signed number of
606 arbitrary size, possibly embedded in whitespace;
607 this behaves identical to
\code{string.atol(
\var{x
})
}. The
608 \var{radix
} argument is interpreted in the same way as for
609 \function{int()
}, and may only be given when
\var{x
} is a string.
610 Otherwise, the argument may be a plain or
611 long integer or a floating point number, and a long integer with
612 the same value is returned. Conversion of floating
613 point numbers to integers truncates (towards zero). If no arguments
614 are given, returns
\code{0L}.
617 \begin{funcdesc
}{map
}{function, list, ...
}
618 Apply
\var{function
} to every item of
\var{list
} and return a list
619 of the results. If additional
\var{list
} arguments are passed,
620 \var{function
} must take that many arguments and is applied to the
621 items of all lists in parallel; if a list is shorter than another it
622 is assumed to be extended with
\code{None
} items. If
\var{function
}
623 is
\code{None
}, the identity function is assumed; if there are
624 multiple list arguments,
\function{map()
} returns a list consisting
625 of tuples containing the corresponding items from all lists (a kind
626 of transpose operation). The
\var{list
} arguments may be any kind
627 of sequence; the result is always a list.
630 \begin{funcdesc
}{max
}{s
\optional{, args...
}}
631 With a single argument
\var{s
}, return the largest item of a
632 non-empty sequence (such as a string, tuple or list). With more
633 than one argument, return the largest of the arguments.
636 \begin{funcdesc
}{min
}{s
\optional{, args...
}}
637 With a single argument
\var{s
}, return the smallest item of a
638 non-empty sequence (such as a string, tuple or list). With more
639 than one argument, return the smallest of the arguments.
642 \begin{funcdesc
}{object
}{}
643 Return a new featureless object.
\function{object()
} is a base
644 for all new style classes. It has the methods that are common
645 to all instances of new style classes.
648 \versionchanged[This function does not accept any arguments.
649 Formerly, it accepted arguments but ignored them
]{2.3}
652 \begin{funcdesc
}{oct
}{x
}
653 Convert an integer number (of any size) to an octal string. The
654 result is a valid Python expression. Note: this always yields an
655 unsigned literal. For example, on a
32-bit machine,
\code{oct(-
1)
}
656 yields
\code{'
037777777777'
}. When evaluated on a machine with the
657 same word size, this literal is evaluated as -
1; at a different word
658 size, it may turn up as a large positive number or raise an
659 \exception{OverflowError
} exception.
662 \begin{funcdesc
}{open
}{filename
\optional{, mode
\optional{, bufsize
}}}
663 An alias for the
\function{file()
} function above.
666 \begin{funcdesc
}{ord
}{c
}
667 Return the
\ASCII{} value of a string of one character or a Unicode
668 character. E.g.,
\code{ord('a')
} returns the integer
\code{97},
669 \code{ord(u'
\e u2020')
} returns
\code{8224}. This is the inverse of
670 \function{chr()
} for strings and of
\function{unichr()
} for Unicode
674 \begin{funcdesc
}{pow
}{x, y
\optional{, z
}}
675 Return
\var{x
} to the power
\var{y
}; if
\var{z
} is present, return
676 \var{x
} to the power
\var{y
}, modulo
\var{z
} (computed more
677 efficiently than
\code{pow(
\var{x
},
\var{y
}) \%\
\var{z
}}). The
678 arguments must have numeric types. With mixed operand types, the
679 coercion rules for binary arithmetic operators apply. For int and
680 long int operands, the result has the same type as the operands
681 (after coercion) unless the second argument is negative; in that
682 case, all arguments are converted to float and a float result is
683 delivered. For example,
\code{10**
2} returns
\code{100}, but
684 \code{10**-
2} returns
\code{0.01}. (This last feature was added in
685 Python
2.2. In Python
2.1 and before, if both arguments were of integer
686 types and the second argument was negative, an exception was raised.)
687 If the second argument is negative, the third argument must be omitted.
688 If
\var{z
} is present,
\var{x
} and
\var{y
} must be of integer types,
689 and
\var{y
} must be non-negative. (This restriction was added in
690 Python
2.2. In Python
2.1 and before, floating
3-argument
\code{pow()
}
691 returned platform-dependent results depending on floating-point
695 \begin{funcdesc
}{property
}{\optional{fget
\optional{, fset
\optional{,
696 fdel
\optional{, doc
}}}}}
697 Return a property attribute for new-style classes (classes that
698 derive from
\class{object
}).
700 \var{fget
} is a function for getting an attribute value, likewise
701 \var{fset
} is a function for setting, and
\var{fdel
} a function
702 for del'ing, an attribute. Typical use is to define a managed attribute x:
706 def getx(self): return self.__x
707 def setx(self, value): self.__x = value
708 def delx(self): del self.__x
709 x = property(getx, setx, delx, "I'm the 'x' property.")
715 \begin{funcdesc
}{range
}{\optional{start,
} stop
\optional{, step
}}
716 This is a versatile function to create lists containing arithmetic
717 progressions. It is most often used in
\keyword{for
} loops. The
718 arguments must be plain integers. If the
\var{step
} argument is
719 omitted, it defaults to
\code{1}. If the
\var{start
} argument is
720 omitted, it defaults to
\code{0}. The full form returns a list of
721 plain integers
\code{[\var{start
},
\var{start
} +
\var{step
},
722 \var{start
} +
2 *
\var{step
},
\ldots]}. If
\var{step
} is positive,
723 the last element is the largest
\code{\var{start
} +
\var{i
} *
724 \var{step
}} less than
\var{stop
}; if
\var{step
} is negative, the last
725 element is the largest
\code{\var{start
} +
\var{i
} *
\var{step
}}
726 greater than
\var{stop
}.
\var{step
} must not be zero (or else
727 \exception{ValueError
} is raised). Example:
731 [0,
1,
2,
3,
4,
5,
6,
7,
8,
9]
733 [1,
2,
3,
4,
5,
6,
7,
8,
9,
10]
735 [0,
5,
10,
15,
20,
25]
738 >>> range(
0, -
10, -
1)
739 [0, -
1, -
2, -
3, -
4, -
5, -
6, -
7, -
8, -
9]
747 \begin{funcdesc
}{raw_input
}{\optional{prompt
}}
748 If the
\var{prompt
} argument is present, it is written to standard output
749 without a trailing newline. The function then reads a line from input,
750 converts it to a string (stripping a trailing newline), and returns that.
751 When
\EOF{} is read,
\exception{EOFError
} is raised. Example:
754 >>> s = raw_input('--> ')
755 --> Monty Python's Flying Circus
757 "Monty Python's Flying Circus"
760 If the
\refmodule{readline
} module was loaded, then
761 \function{raw_input()
} will use it to provide elaborate
762 line editing and history features.
765 \begin{funcdesc
}{reduce
}{function, sequence
\optional{, initializer
}}
766 Apply
\var{function
} of two arguments cumulatively to the items of
767 \var{sequence
}, from left to right, so as to reduce the sequence to
768 a single value. For example,
\code{reduce(lambda x, y: x+y,
[1,
2,
769 3,
4,
5])
} calculates
\code{((((
1+
2)+
3)+
4)+
5)
}. The left argument,
770 \var{x
}, is the accumulated value and the right argument,
\var{y
},
771 is the update value from the
\var{sequence
}. If the optional
772 \var{initializer
} is present, it is placed before the items of the
773 sequence in the calculation, and serves as a default when the
774 sequence is empty. If
\var{initializer
} is not given and
775 \var{sequence
} contains only one item, the first item is returned.
778 \begin{funcdesc
}{reload
}{module
}
779 Re-parse and re-initialize an already imported
\var{module
}. The
780 argument must be a module object, so it must have been successfully
781 imported before. This is useful if you have edited the module
782 source file using an external editor and want to try out the new
783 version without leaving the Python interpreter. The return value is
784 the module object (the same as the
\var{module
} argument).
786 There are a number of caveats:
788 If a module is syntactically correct but its initialization fails,
789 the first
\keyword{import
} statement for it does not bind its name
790 locally, but does store a (partially initialized) module object in
791 \code{sys.modules
}. To reload the module you must first
792 \keyword{import
} it again (this will bind the name to the partially
793 initialized module object) before you can
\function{reload()
} it.
795 When a module is reloaded, its dictionary (containing the module's
796 global variables) is retained. Redefinitions of names will override
797 the old definitions, so this is generally not a problem. If the new
798 version of a module does not define a name that was defined by the
799 old version, the old definition remains. This feature can be used
800 to the module's advantage if it maintains a global table or cache of
801 objects --- with a
\keyword{try
} statement it can test for the
802 table's presence and skip its initialization if desired.
804 It is legal though generally not very useful to reload built-in or
805 dynamically loaded modules, except for
\refmodule{sys
},
806 \refmodule[main
]{__main__
} and
\refmodule[builtin
]{__builtin__
}. In
807 many cases, however, extension modules are not designed to be
808 initialized more than once, and may fail in arbitrary ways when
811 If a module imports objects from another module using
\keyword{from
}
812 \ldots{} \keyword{import
} \ldots{}, calling
\function{reload()
} for
813 the other module does not redefine the objects imported from it ---
814 one way around this is to re-execute the
\keyword{from
} statement,
815 another is to use
\keyword{import
} and qualified names
816 (
\var{module
}.
\var{name
}) instead.
818 If a module instantiates instances of a class, reloading the module
819 that defines the class does not affect the method definitions of the
820 instances --- they continue to use the old class definition. The
821 same is true for derived classes.
824 \begin{funcdesc
}{repr
}{object
}
825 Return a string containing a printable representation of an object.
826 This is the same value yielded by conversions (reverse quotes).
827 It is sometimes useful to be able to access this operation as an
828 ordinary function. For many types, this function makes an attempt
829 to return a string that would yield an object with the same value
830 when passed to
\function{eval()
}.
833 \begin{funcdesc
}{round
}{x
\optional{, n
}}
834 Return the floating point value
\var{x
} rounded to
\var{n
} digits
835 after the decimal point. If
\var{n
} is omitted, it defaults to zero.
836 The result is a floating point number. Values are rounded to the
837 closest multiple of
10 to the power minus
\var{n
}; if two multiples
838 are equally close, rounding is done away from
0 (so. for example,
839 \code{round(
0.5)
} is
\code{1.0} and
\code{round(-
0.5)
} is
\code{-
1.0}).
842 \begin{funcdesc
}{setattr
}{object, name, value
}
843 This is the counterpart of
\function{getattr()
}. The arguments are an
844 object, a string and an arbitrary value. The string may name an
845 existing attribute or a new attribute. The function assigns the
846 value to the attribute, provided the object allows it. For example,
847 \code{setattr(
\var{x
}, '
\var{foobar
}',
123)
} is equivalent to
848 \code{\var{x
}.
\var{foobar
} =
123}.
851 \begin{funcdesc
}{slice
}{\optional{start,
} stop
\optional{, step
}}
852 Return a slice object representing the set of indices specified by
853 \code{range(
\var{start
},
\var{stop
},
\var{step
})
}. The
\var{start
}
854 and
\var{step
} arguments default to
\code{None
}. Slice objects have
855 read-only data attributes
\member{start
},
\member{stop
} and
856 \member{step
} which merely return the argument values (or their
857 default). They have no other explicit functionality; however they
858 are used by Numerical Python
\index{Numerical Python
} and other third
859 party extensions. Slice objects are also generated when extended
860 indexing syntax is used. For example:
\samp{a
[start:stop:step
]} or
861 \samp{a
[start:stop, i
]}.
864 \begin{funcdesc
}{staticmethod
}{function
}
865 Return a static method for
\var{function
}.
867 A static method does not receive an implicit first argument.
868 To declare a static method, use this idiom:
872 def f(arg1, arg2, ...): ...
876 It can be called either on the class (such as
\code{C.f()
}) or on an
877 instance (such as
\code{C().f()
}). The instance is ignored except
880 Static methods in Python are similar to those found in Java or
\Cpp.
881 For a more advanced concept, see
\function{classmethod()
} in this
886 \begin{funcdesc
}{str
}{\optional{object
}}
887 Return a string containing a nicely printable representation of an
888 object. For strings, this returns the string itself. The
889 difference with
\code{repr(
\var{object
})
} is that
890 \code{str(
\var{object
})
} does not always attempt to return a string
891 that is acceptable to
\function{eval()
}; its goal is to return a
892 printable string. If no argument is given, returns the empty
896 \begin{funcdesc
}{sum
}{sequence
\optional{, start
}}
897 Sums
\var{start
} and the items of a
\var{sequence
}, from left to
898 right, and returns the total.
\var{start
} defaults to
\code{0}.
899 The
\var{sequence
}'s items are normally numbers, and are not allowed
900 to be strings. The fast, correct way to concatenate sequence of
901 strings is by calling
\code{''.join(
\var{sequence
})
}.
902 Note that
\code{sum(range(
\var{n
}),
\var{m
})
} is equivalent to
903 \code{reduce(operator.add, range(
\var{n
}),
\var{m
})
}
907 \begin{funcdesc
}{super
}{type
\optional{, object-or-type
}}
908 Return the superclass of
\var{type
}. If the second argument is omitted
909 the super object returned is unbound. If the second argument is an
910 object,
\code{isinstance(
\var{obj
},
\var{type
})
} must be true. If
911 the second argument is a type,
\code{issubclass(
\var{type2
},
912 \var{type
})
} must be true.
913 \function{super()
} only works for new-style classes.
915 A typical use for calling a cooperative superclass method is:
919 super(C, self).meth(arg)
924 \begin{funcdesc
}{tuple
}{\optional{sequence
}}
925 Return a tuple whose items are the same and in the same order as
926 \var{sequence
}'s items.
\var{sequence
} may be a sequence, a
927 container that supports iteration, or an iterator object.
928 If
\var{sequence
} is already a tuple, it
929 is returned unchanged. For instance,
\code{tuple('abc')
} returns
930 \code{('a', 'b', 'c')
} and
\code{tuple(
[1,
2,
3])
} returns
931 \code{(
1,
2,
3)
}. If no argument is given, returns a new empty
935 \begin{funcdesc
}{type
}{object
}
936 Return the type of an
\var{object
}. The return value is a
937 type
\obindex{type
} object. The standard module
938 \module{types
}\refstmodindex{types
} defines names for all built-in
939 types that don't already have built-in names.
945 >>> if type(x) is str: print "It's a string"
950 >>> if type(f) is types.FunctionType: print "It's a function"
955 The
\function{isinstance()
} built-in function is recommended for
956 testing the type of an object.
959 \begin{funcdesc
}{unichr
}{i
}
960 Return the Unicode string of one character whose Unicode code is the
961 integer
\var{i
}. For example,
\code{unichr(
97)
} returns the string
962 \code{u'a'
}. This is the inverse of
\function{ord()
} for Unicode
963 strings. The argument must be in the range
[0.
.65535], inclusive.
964 \exception{ValueError
} is raised otherwise.
968 \begin{funcdesc
}{unicode
}{\optional{object
\optional{, encoding
969 \optional{, errors
}}}}
970 Return the Unicode string version of
\var{object
} using one of the
973 If
\var{encoding
} and/or
\var{errors
} are given,
\code{unicode()
}
974 will decode the object which can either be an
8-bit string or a
975 character buffer using the codec for
\var{encoding
}. The
976 \var{encoding
} parameter is a string giving the name of an encoding;
977 if the encoding is not known,
\exception{LookupError
} is raised.
978 Error handling is done according to
\var{errors
}; this specifies the
979 treatment of characters which are invalid in the input encoding. If
980 \var{errors
} is
\code{'strict'
} (the default), a
981 \exception{ValueError
} is raised on errors, while a value of
982 \code{'ignore'
} causes errors to be silently ignored, and a value of
983 \code{'replace'
} causes the official Unicode replacement character,
984 \code{U+FFFD
}, to be used to replace input characters which cannot
985 be decoded. See also the
\refmodule{codecs
} module.
987 If no optional parameters are given,
\code{unicode()
} will mimic the
988 behaviour of
\code{str()
} except that it returns Unicode strings
989 instead of
8-bit strings. More precisely, if
\var{object
} is a
990 Unicode string or subclass it will return that Unicode string without
991 any additional decoding applied.
993 For objects which provide a
\method{__unicode__()
} method, it will
994 call this method without arguments to create a Unicode string. For
995 all other objects, the
8-bit string version or representation is
996 requested and then converted to a Unicode string using the codec for
997 the default encoding in
\code{'strict'
} mode.
1000 \versionchanged[Support for
\method{__unicode__()
} added
]{2.2}
1003 \begin{funcdesc
}{vars
}{\optional{object
}}
1004 Without arguments, return a dictionary corresponding to the current
1005 local symbol table. With a module, class or class instance object
1006 as argument (or anything else that has a
\member{__dict__
}
1007 attribute), returns a dictionary corresponding to the object's
1008 symbol table. The returned dictionary should not be modified: the
1009 effects on the corresponding symbol table are undefined.
\footnote{
1010 In the current implementation, local variable bindings cannot
1011 normally be affected this way, but variables retrieved from
1012 other scopes (such as modules) can be. This may change.
}
1015 \begin{funcdesc
}{xrange
}{\optional{start,
} stop
\optional{, step
}}
1016 This function is very similar to
\function{range()
}, but returns an
1017 ``xrange object'' instead of a list. This is an opaque sequence
1018 type which yields the same values as the corresponding list, without
1019 actually storing them all simultaneously. The advantage of
1020 \function{xrange()
} over
\function{range()
} is minimal (since
1021 \function{xrange()
} still has to create the values when asked for
1022 them) except when a very large range is used on a memory-starved
1023 machine or when all of the range's elements are never used (such as
1024 when the loop is usually terminated with
\keyword{break
}).
1027 \begin{funcdesc
}{zip
}{seq1,
\moreargs}
1028 This function returns a list of tuples, where the
\var{i
}-th tuple contains
1029 the
\var{i
}-th element from each of the argument sequences. At
1030 least one sequence is required, otherwise a
\exception{TypeError
} is
1031 raised. The returned list is truncated in length to the length of
1032 the shortest argument sequence. When there are multiple argument
1033 sequences which are all of the same length,
\function{zip()
} is
1034 similar to
\function{map()
} with an initial argument of
\code{None
}.
1035 With a single sequence argument, it returns a list of
1-tuples.
1040 % ---------------------------------------------------------------------------
1043 \section{Non-essential Built-in Functions
\label{non-essential-built-in-funcs
}}
1045 There are several built-in functions that are no longer essential to learn,
1046 know or use in modern Python programming. They have been kept here to
1047 maintain backwards compatability with programs written for older versions
1050 Python programmers, trainers, students and bookwriters should feel free to
1051 bypass these functions without concerns about missing something important.
1054 \setindexsubitem{(non-essential built-in functions)
}
1056 \begin{funcdesc
}{apply
}{function, args
\optional{, keywords
}}
1057 The
\var{function
} argument must be a callable object (a
1058 user-defined or built-in function or method, or a class object) and
1059 the
\var{args
} argument must be a sequence. The
\var{function
} is
1060 called with
\var{args
} as the argument list; the number of arguments
1061 is the length of the tuple.
1062 If the optional
\var{keywords
} argument is present, it must be a
1063 dictionary whose keys are strings. It specifies keyword arguments
1064 to be added to the end of the argument list.
1065 Calling
\function{apply()
} is different from just calling
1066 \code{\var{function
}(
\var{args
})
}, since in that case there is always
1067 exactly one argument. The use of
\function{apply()
} is equivalent
1068 to
\code{\var{function
}(*\var{args}, **\var{keywords})}.
1069 Use of \function{apply()} is not necessary since the ``extended call
1070 syntax,'' as used in the last example, is completely equivalent.
1072 \deprecated{2.3}{Use the extended call syntax instead, as described
1076 \begin{funcdesc}{buffer}{object\optional{, offset\optional{, size}}}
1077 The \var{object} argument must be an object that supports the buffer
1078 call interface (such as strings, arrays, and buffers). A new buffer
1079 object will be created which references the \var{object} argument.
1080 The buffer object will be a slice from the beginning of \var{object}
1081 (or from the specified \var{offset}). The slice will extend to the
1082 end of \var{object} (or will have a length given by the \var{size}
1086 \begin{funcdesc}{coerce}{x, y}
1087 Return a tuple consisting of the two numeric arguments converted to
1088 a common type, using the same rules as used by arithmetic
1092 \begin{funcdesc}{intern}{string}
1093 Enter \var{string} in the table of ``interned'' strings and return
1094 the interned string -- which is \var{string} itself or a copy.
1095 Interning strings is useful to gain a little performance on
1096 dictionary lookup -- if the keys in a dictionary are interned, and
1097 the lookup key is interned, the key comparisons (after hashing) can
1098 be done by a pointer compare instead of a string compare. Normally,
1099 the names used in Python programs are automatically interned, and
1100 the dictionaries used to hold module, class or instance attributes
1101 have interned keys. \versionchanged[Interned strings are not
1102 immortal (like they used to be in Python 2.2 and before);
1103 you must keep a reference to the return value of \function{intern()}
1104 around to benefit from it]{2.3}