\section{Built-in Functions \label{built-in-funcs}} The Python interpreter has a number of functions built into it thatare always available. They are listed here in alphabetical order. \setindexsubitem{(built-in function)} \begin{funcdesc}{__import__}{name\optional{, globals\optional{, locals\optional{, fromlist\optional{, level}}}}} This function is invoked by the \keyword{import}\stindex{import} statement. It mainly exists so that you can replace it with another function that has a compatible interface, in order to change the semantics of the \keyword{import} statement. For examples of why and how you would do this, see the standard library modules \module{ihooks}\refstmodindex{ihooks} and \refmodule{rexec}\refstmodindex{rexec}. See also the built-in module \refmodule{imp}\refbimodindex{imp}, which defines some useful operations out of which you can build your own \function{__import__()} function. For example, the statement \samp{import spam} results in the following call: \code{__import__('spam',} \code{globals(),} \code{locals(), [], -1)}; the statement \samp{from spam.ham import eggs} results in \samp{__import__('spam.ham', globals(), locals(), ['eggs'], -1)}. Note that even though \code{locals()} and \code{['eggs']} are passed in as arguments, the \function{__import__()} function does not set the local variable named \code{eggs}; this is done by subsequent code that is generated for the import statement. (In fact, the standard implementation does not use its \var{locals} argument at all, and uses its \var{globals} only to determine the package context of the \keyword{import} statement.) When the \var{name} variable is of the form \code{package.module}, normally, the top-level package (the name up till the first dot) is returned, \emph{not} the module named by \var{name}. However, when a non-empty \var{fromlist} argument is given, the module named by \var{name} is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using \samp{import spam.ham.eggs}, the top-level package \module{spam} must be placed in the importing namespace, but when using \samp{from spam.ham import eggs}, the \code{spam.ham} subpackage must be used to find the \code{eggs} variable. As a workaround for this behavior, use \function{getattr()} to extract the desired components. For example, you could define the following helper: \begin{verbatim}def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod\end{verbatim} \var{level} specifies whether to use absolute or relative imports. The default is \code{-1} which indicates both absolute and relative imports will be attempted. \code{0} means only perform absolute imports. Positive values for \var{level} indicate the number of parent directories to search relative to the directory of the module calling \function{__import__}.\versionchanged[The level parameter was added]{2.5}\versionchanged[Keyword support for parameters was added]{2.5}\end{funcdesc} \begin{funcdesc}{abs}{x} Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.\end{funcdesc} \begin{funcdesc}{all}{iterable} Return True if all elements of the \var{iterable} are true. Equivalent to: \begin{verbatim} def all(iterable): for element in iterable: if not element: return False return True \end{verbatim} \versionadded{2.5}\end{funcdesc} \begin{funcdesc}{any}{iterable} Return True if any element of the \var{iterable} is true. Equivalent to: \begin{verbatim} def any(iterable): for element in iterable: if element: return True return False \end{verbatim} \versionadded{2.5}\end{funcdesc} \begin{funcdesc}{basestring}{} This abstract type is the superclass for \class{str} and \class{unicode}. It cannot be called or instantiated, but it can be used to test whether an object is an instance of \class{str} or \class{unicode}. \code{isinstance(obj, basestring)} is equivalent to \code{isinstance(obj, (str, unicode))}. \versionadded{2.3}\end{funcdesc} \begin{funcdesc}{bool}{\optional{x}} Convert a value to a Boolean, using the standard truth testing procedure. If \var{x} is false or omitted, this returns \constant{False}; otherwise it returns \constant{True}. \class{bool} is also a class, which is a subclass of \class{int}. Class \class{bool} cannot be subclassed further. Its only instances are \constant{False} and \constant{True}. \indexii{Boolean}{type} \versionadded{2.2.1} \versionchanged[If no argument is given, this function returns \constant{False}]{2.3}\end{funcdesc} \begin{funcdesc}{callable}{object} Return true if the \var{object} argument appears callable, false if not. If this returns true, it is still possible that a call fails, but if it is false, calling \var{object} will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a \method{__call__()} method.\end{funcdesc} \begin{funcdesc}{chr}{i} Return a string of one character whose \ASCII{} code is the integer \var{i}. For example, \code{chr(97)} returns the string \code{'a'}. This is the inverse of \function{ord()}. The argument must be in the range [0..255], inclusive; \exception{ValueError} will be raised if \var{i} is outside that range.\end{funcdesc} \begin{funcdesc}{classmethod}{function} Return a class method for \var{function}. A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: \begin{verbatim}class C: @classmethod def f(cls, arg1, arg2, ...): ...\end{verbatim} The \code{@classmethod} form is a function decorator -- see the description of function definitions in chapter 7 of the \citetitle[../ref/ref.html]{Python Reference Manual} for details. It can be called either on the class (such as \code{C.f()}) or on an instance (such as \code{C().f()}). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than \Cpp{} or Java static methods. If you want those, see \function{staticmethod()} in this section. For more information on class methods, consult the documentation on the standard type hierarchy in chapter 3 of the \citetitle[../ref/types.html]{Python Reference Manual} (at the bottom). \versionadded{2.2} \versionchanged[Function decorator syntax added]{2.4}\end{funcdesc} \begin{funcdesc}{cmp}{x, y} Compare the two objects \var{x} and \var{y} and return an integer according to the outcome. The return value is negative if \code{\var{x} < \var{y}}, zero if \code{\var{x} == \var{y}} and strictly positive if \code{\var{x} > \var{y}}.\end{funcdesc} \begin{funcdesc}{compile}{string, filename, kind\optional{, flags\optional{, dont_inherit}}} Compile the \var{string} into a code object. Code objects can be executed by an \keyword{exec} statement or evaluated by a call to \function{eval()}. The \var{filename} argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file (\code{'<string>'} is commonly used). The \var{kind} argument specifies what kind of code must be compiled; it can be \code{'exec'} if \var{string} consists of a sequence of statements, \code{'eval'} if it consists of a single expression, or \code{'single'} if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something else than \code{None} will be printed). When compiling multi-line statements, two caveats apply: line endings must be represented by a single newline character (\code{'\e n'}), and the input must be terminated by at least one newline character. If line endings are represented by \code{'\e r\e n'}, use the string \method{replace()} method to change them into \code{'\e n'}. The optional arguments \var{flags} and \var{dont_inherit} (which are new in Python 2.2) control which future statements (see \pep{236}) affect the compilation of \var{string}. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile. If the \var{flags} argument is given and \var{dont_inherit} is not (or is zero) then the future statements specified by the \var{flags} argument are used in addition to those that would be used anyway. If \var{dont_inherit} is a non-zero integer then the \var{flags} argument is it -- the future statements in effect around the call to compile are ignored. Future statements are specified by bits which can be bitwise or-ed together to specify multiple statements. The bitfield required to specify a given feature can be found as the \member{compiler_flag} attribute on the \class{_Feature} instance in the \module{__future__} module.\end{funcdesc} \begin{funcdesc}{complex}{\optional{real\optional{, imag}}} Create a complex number with the value \var{real} + \var{imag}*j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If \var{imag} is omitted, it defaults to zero and the function serves as a numeric conversion function like \function{int()}, \function{long()} and \function{float()}. If both arguments are omitted, returns \code{0j}.\end{funcdesc} \begin{funcdesc}{delattr}{object, name} This is a relative of \function{setattr()}. The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it. For example, \code{delattr(\var{x}, '\var{foobar}')} is equivalent to \code{del \var{x}.\var{foobar}}.\end{funcdesc} \begin{funcdesc}{dict}{\optional{arg}} Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. If the positional argument \var{arg} is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. Otherwise the positional argument must be a sequence, a container that supports iteration, or an iterator object. The elements of the argument must each also be of one of those kinds, and each must in turn contain exactly two objects. The first is used as a key in the new dictionary, and the second as the key's value. If a given key is seen more than once, the last value associated with it is retained in the new dictionary. If keyword arguments are given, the keywords themselves with their associated values are added as items to the dictionary. If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained in the dictionary. For example, these all return a dictionary equal to \code{\{"one": 2, "two": 3\}}: \begin{itemize} \item \code{dict(\{'one': 2, 'two': 3\})} \item \code{dict(\{'one': 2, 'two': 3\}.items())} \item \code{dict(\{'one': 2, 'two': 3\}.iteritems())} \item \code{dict(zip(('one', 'two'), (2, 3)))} \item \code{dict([['two', 3], ['one', 2]])} \item \code{dict(one=2, two=3)} \item \code{dict([(['one', 'two'][i-2], i) for i in (2, 3)])} \end{itemize} \versionadded{2.2} \versionchanged[Support for building a dictionary from keyword arguments added]{2.3}\end{funcdesc} \begin{funcdesc}{dir}{\optional{object}} Without arguments, return the list of names in the current local symbol table. With an argument, attempts to return a list of valid attributes for that object. This information is gleaned from the object's \member{__dict__} attribute, if defined, and from the class or type object. The list is not necessarily complete. If the object is a module object, the list contains the names of the module's attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes. The resulting list is sorted alphabetically. For example: \begin{verbatim}>>> import struct>>> dir()['__builtins__', '__doc__', '__name__', 'struct']>>> dir(struct)['__doc__', '__name__', 'calcsize', 'error', 'pack', 'unpack']\end{verbatim} \note{Because \function{dir()} is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases.}\end{funcdesc} \begin{funcdesc}{divmod}{a, b} Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as \code{(\var{a} // \var{b}, \var{a} \%{} \var{b})}. For floating point numbers the result is \code{(\var{q}, \var{a} \%{} \var{b})}, where \var{q} is usually \code{math.floor(\var{a} / \var{b})} but may be 1 less than that. In any case \code{\var{q} * \var{b} + \var{a} \%{} \var{b}} is very close to \var{a}, if \code{\var{a} \%{} \var{b}} is non-zero it has the same sign as \var{b}, and \code{0 <= abs(\var{a} \%{} \var{b}) < abs(\var{b})}. \versionchanged[Using \function{divmod()} with complex numbers is deprecated]{2.3}\end{funcdesc} \begin{funcdesc}{enumerate}{iterable} Return an enumerate object. \var{iterable} must be a sequence, an iterator, or some other object which supports iteration. The \method{next()} method of the iterator returned by \function{enumerate()} returns a tuple containing a count (from zero) and the corresponding value obtained from iterating over \var{iterable}. \function{enumerate()} is useful for obtaining an indexed series: \code{(0, seq[0])}, \code{(1, seq[1])}, \code{(2, seq[2])}, \ldots. \versionadded{2.3}\end{funcdesc} \begin{funcdesc}{eval}{expression\optional{, globals\optional{, locals}}} The arguments are a string and optional globals and locals. If provided, \var{globals} must be a dictionary. If provided, \var{locals} can be any mapping object. \versionchanged[formerly \var{locals} was required to be a dictionary]{2.4} The \var{expression} argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the \var{globals} and \var{locals} dictionaries as global and local name space. If the \var{globals} dictionary is present and lacks '__builtins__', the current globals are copied into \var{globals} before \var{expression} is parsed. This means that \var{expression} normally has full access to the standard \refmodule[builtin]{__builtin__} module and restricted environments are propagated. If the \var{locals} dictionary is omitted it defaults to the \var{globals} dictionary. If both dictionaries are omitted, the expression is executed in the environment where \keyword{eval} is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example: \begin{verbatim}>>> x = 1>>> print eval('x+1')2\end{verbatim} This function can also be used to execute arbitrary code objects (such as those created by \function{compile()}). In this case pass a code object instead of a string. The code object must have been compiled passing \code{'eval'} as the \var{kind} argument. Hints: dynamic execution of statements is supported by the \keyword{exec} statement. Execution of statements from a file is supported by the \function{execfile()} function. The \function{globals()} and \function{locals()} functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by \function{eval()} or \function{execfile()}.\end{funcdesc} \begin{funcdesc}{execfile}{filename\optional{, globals\optional{, locals}}} This function is similar to the \keyword{exec} statement, but parses a file instead of a string. It is different from the \keyword{import} statement in that it does not use the module administration --- it reads the file unconditionally and does not create a new module.\footnote{It is used relatively rarely so does not warrant being made into a statement.} The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the \var{globals} and \var{locals} dictionaries as global and local namespace. If provided, \var{locals} can be any mapping object. \versionchanged[formerly \var{locals} was required to be a dictionary]{2.4} If the \var{locals} dictionary is omitted it defaults to the \var{globals} dictionary. If both dictionaries are omitted, the expression is executed in the environment where \function{execfile()} is called. The return value is \code{None}. \warning{The default \var{locals} act as described for function \function{locals()} below: modifications to the default \var{locals} dictionary should not be attempted. Pass an explicit \var{locals} dictionary if you need to see effects of the code on \var{locals} after function \function{execfile()} returns. \function{execfile()} cannot be used reliably to modify a function's locals.}\end{funcdesc} \begin{funcdesc}{file}{filename\optional{, mode\optional{, bufsize}}} Constructor function for the \class{file} type, described further in section~\ref{bltin-file-objects}, ``\ulink{File Objects}{bltin-file-objects.html}''. The constructor's arguments are the same as those of the \function{open()} built-in function described below. When opening a file, it's preferable to use \function{open()} instead of invoking this constructor directly. \class{file} is more suited to type testing (for example, writing \samp{isinstance(f, file)}). \versionadded{2.2}\end{funcdesc} \begin{funcdesc}{filter}{function, iterable} Construct a list from those elements of \var{iterable} for which \var{function} returns true. \var{iterable} may be either a sequence, a container which supports iteration, or an iterator, If \var{iterable} is a string or a tuple, the result also has that type; otherwise it is always a list. If \var{function} is \code{None}, the identity function is assumed, that is, all elements of \var{iterable} that are false are removed. Note that \code{filter(function, \var{iterable})} is equivalent to \code{[item for item in \var{iterable} if function(item)]} if function is not \code{None} and \code{[item for item in \var{iterable} if item]} if function is \code{None}.\end{funcdesc} \begin{funcdesc}{float}{\optional{x}} Convert a string or a number to floating point. If the argument is a string, it must contain a possibly signed decimal or floating point number, possibly embedded in whitespace. Otherwise, the argument may be a plain or long integer or a floating point number, and a floating point number with the same value (within Python's floating point precision) is returned. If no argument is given, returns \code{0.0}. \note{When passing in a string, values for NaN\index{NaN} and Infinity\index{Infinity} may be returned, depending on the underlying C library. The specific set of strings accepted which cause these values to be returned depends entirely on the C library and is known to vary.}\end{funcdesc} \begin{funcdesc}{frozenset}{\optional{iterable}} Return a frozenset object whose elements are taken from \var{iterable}. Frozensets are sets that have no update methods but can be hashed and used as members of other sets or as dictionary keys. The elements of a frozenset must be immutable themselves. To represent sets of sets, the inner sets should also be \class{frozenset} objects. If \var{iterable} is not specified, returns a new empty set, \code{frozenset([])}. \versionadded{2.4}\end{funcdesc} \begin{funcdesc}{getattr}{object, name\optional{, default}} Return the value of the named attributed of \var{object}. \var{name} must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, \code{getattr(x, 'foobar')} is equivalent to \code{x.foobar}. If the named attribute does not exist, \var{default} is returned if provided, otherwise \exception{AttributeError} is raised.\end{funcdesc} \begin{funcdesc}{globals}{} Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).\end{funcdesc} \begin{funcdesc}{hasattr}{object, name} The arguments are an object and a string. The result is \code{True} if the string is the name of one of the object's attributes, \code{False} if not. (This is implemented by calling \code{getattr(\var{object}, \var{name})} and seeing whether it raises an exception or not.)\end{funcdesc} \begin{funcdesc}{hash}{object} Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).\end{funcdesc} \begin{funcdesc}{help}{\optional{object}} Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated. \versionadded{2.2}\end{funcdesc} \begin{funcdesc}{hex}{x}Lines 1–500 of 1321. Load more
\section{Built-in Functions \label{built-in-funcs}} The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order. \setindexsubitem{(built-in function)} \begin{funcdesc}{__import__}{name\optional{, globals\optional{, locals\optional{, fromlist\optional{, level}}}}} This function is invoked by the \keyword{import}\stindex{import} statement. It mainly exists so that you can replace it with another function that has a compatible interface, in order to change the semantics of the \keyword{import} statement. For examples of why and how you would do this, see the standard library modules \module{ihooks}\refstmodindex{ihooks} and \refmodule{rexec}\refstmodindex{rexec}. See also the built-in module \refmodule{imp}\refbimodindex{imp}, which defines some useful operations out of which you can build your own \function{__import__()} function. For example, the statement \samp{import spam} results in the following call: \code{__import__('spam',} \code{globals(),} \code{locals(), [], -1)}; the statement \samp{from spam.ham import eggs} results in \samp{__import__('spam.ham', globals(), locals(), ['eggs'], -1)}. Note that even though \code{locals()} and \code{['eggs']} are passed in as arguments, the \function{__import__()} function does not set the local variable named \code{eggs}; this is done by subsequent code that is generated for the import statement. (In fact, the standard implementation does not use its \var{locals} argument at all, and uses its \var{globals} only to determine the package context of the \keyword{import} statement.) When the \var{name} variable is of the form \code{package.module}, normally, the top-level package (the name up till the first dot) is returned, \emph{not} the module named by \var{name}. However, when a non-empty \var{fromlist} argument is given, the module named by \var{name} is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using \samp{import spam.ham.eggs}, the top-level package \module{spam} must be placed in the importing namespace, but when using \samp{from spam.ham import eggs}, the \code{spam.ham} subpackage must be used to find the \code{eggs} variable. As a workaround for this behavior, use \function{getattr()} to extract the desired components. For example, you could define the following helper: \begin{verbatim} def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod \end{verbatim} \var{level} specifies whether to use absolute or relative imports. The default is \code{-1} which indicates both absolute and relative imports will be attempted. \code{0} means only perform absolute imports. Positive values for \var{level} indicate the number of parent directories to search relative to the directory of the module calling \function{__import__}. \versionchanged[The level parameter was added]{2.5} \versionchanged[Keyword support for parameters was added]{2.5} \end{funcdesc} \begin{funcdesc}{abs}{x} Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned. \end{funcdesc} \begin{funcdesc}{all}{iterable} Return True if all elements of the \var{iterable} are true. Equivalent to: \begin{verbatim} def all(iterable): for element in iterable: if not element: return False return True \end{verbatim} \versionadded{2.5} \end{funcdesc} \begin{funcdesc}{any}{iterable} Return True if any element of the \var{iterable} is true. Equivalent to: \begin{verbatim} def any(iterable): for element in iterable: if element: return True return False \end{verbatim} \versionadded{2.5} \end{funcdesc} \begin{funcdesc}{basestring}{} This abstract type is the superclass for \class{str} and \class{unicode}. It cannot be called or instantiated, but it can be used to test whether an object is an instance of \class{str} or \class{unicode}. \code{isinstance(obj, basestring)} is equivalent to \code{isinstance(obj, (str, unicode))}. \versionadded{2.3} \end{funcdesc} \begin{funcdesc}{bool}{\optional{x}} Convert a value to a Boolean, using the standard truth testing procedure. If \var{x} is false or omitted, this returns \constant{False}; otherwise it returns \constant{True}. \class{bool} is also a class, which is a subclass of \class{int}. Class \class{bool} cannot be subclassed further. Its only instances are \constant{False} and \constant{True}. \indexii{Boolean}{type} \versionadded{2.2.1} \versionchanged[If no argument is given, this function returns \constant{False}]{2.3} \end{funcdesc} \begin{funcdesc}{callable}{object} Return true if the \var{object} argument appears callable, false if not. If this returns true, it is still possible that a call fails, but if it is false, calling \var{object} will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a \method{__call__()} method. \end{funcdesc} \begin{funcdesc}{chr}{i} Return a string of one character whose \ASCII{} code is the integer \var{i}. For example, \code{chr(97)} returns the string \code{'a'}. This is the inverse of \function{ord()}. The argument must be in the range [0..255], inclusive; \exception{ValueError} will be raised if \var{i} is outside that range. \end{funcdesc} \begin{funcdesc}{classmethod}{function} Return a class method for \var{function}. A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: \begin{verbatim} class C: @classmethod def f(cls, arg1, arg2, ...): ... \end{verbatim} The \code{@classmethod} form is a function decorator -- see the description of function definitions in chapter 7 of the \citetitle[../ref/ref.html]{Python Reference Manual} for details. It can be called either on the class (such as \code{C.f()}) or on an instance (such as \code{C().f()}). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than \Cpp{} or Java static methods. If you want those, see \function{staticmethod()} in this section. For more information on class methods, consult the documentation on the standard type hierarchy in chapter 3 of the \citetitle[../ref/types.html]{Python Reference Manual} (at the bottom). \versionadded{2.2} \versionchanged[Function decorator syntax added]{2.4} \end{funcdesc} \begin{funcdesc}{cmp}{x, y} Compare the two objects \var{x} and \var{y} and return an integer according to the outcome. The return value is negative if \code{\var{x} < \var{y}}, zero if \code{\var{x} == \var{y}} and strictly positive if \code{\var{x} > \var{y}}. \end{funcdesc} \begin{funcdesc}{compile}{string, filename, kind\optional{, flags\optional{, dont_inherit}}} Compile the \var{string} into a code object. Code objects can be executed by an \keyword{exec} statement or evaluated by a call to \function{eval()}. The \var{filename} argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file (\code{'<string>'} is commonly used). The \var{kind} argument specifies what kind of code must be compiled; it can be \code{'exec'} if \var{string} consists of a sequence of statements, \code{'eval'} if it consists of a single expression, or \code{'single'} if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something else than \code{None} will be printed). When compiling multi-line statements, two caveats apply: line endings must be represented by a single newline character (\code{'\e n'}), and the input must be terminated by at least one newline character. If line endings are represented by \code{'\e r\e n'}, use the string \method{replace()} method to change them into \code{'\e n'}. The optional arguments \var{flags} and \var{dont_inherit} (which are new in Python 2.2) control which future statements (see \pep{236}) affect the compilation of \var{string}. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile. If the \var{flags} argument is given and \var{dont_inherit} is not (or is zero) then the future statements specified by the \var{flags} argument are used in addition to those that would be used anyway. If \var{dont_inherit} is a non-zero integer then the \var{flags} argument is it -- the future statements in effect around the call to compile are ignored. Future statements are specified by bits which can be bitwise or-ed together to specify multiple statements. The bitfield required to specify a given feature can be found as the \member{compiler_flag} attribute on the \class{_Feature} instance in the \module{__future__} module. \end{funcdesc} \begin{funcdesc}{complex}{\optional{real\optional{, imag}}} Create a complex number with the value \var{real} + \var{imag}*j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If \var{imag} is omitted, it defaults to zero and the function serves as a numeric conversion function like \function{int()}, \function{long()} and \function{float()}. If both arguments are omitted, returns \code{0j}. \end{funcdesc} \begin{funcdesc}{delattr}{object, name} This is a relative of \function{setattr()}. The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it. For example, \code{delattr(\var{x}, '\var{foobar}')} is equivalent to \code{del \var{x}.\var{foobar}}. \end{funcdesc} \begin{funcdesc}{dict}{\optional{arg}} Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. If the positional argument \var{arg} is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. Otherwise the positional argument must be a sequence, a container that supports iteration, or an iterator object. The elements of the argument must each also be of one of those kinds, and each must in turn contain exactly two objects. The first is used as a key in the new dictionary, and the second as the key's value. If a given key is seen more than once, the last value associated with it is retained in the new dictionary. If keyword arguments are given, the keywords themselves with their associated values are added as items to the dictionary. If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained in the dictionary. For example, these all return a dictionary equal to \code{\{"one": 2, "two": 3\}}: \begin{itemize} \item \code{dict(\{'one': 2, 'two': 3\})} \item \code{dict(\{'one': 2, 'two': 3\}.items())} \item \code{dict(\{'one': 2, 'two': 3\}.iteritems())} \item \code{dict(zip(('one', 'two'), (2, 3)))} \item \code{dict([['two', 3], ['one', 2]])} \item \code{dict(one=2, two=3)} \item \code{dict([(['one', 'two'][i-2], i) for i in (2, 3)])} \end{itemize} \versionadded{2.2} \versionchanged[Support for building a dictionary from keyword arguments added]{2.3} \end{funcdesc} \begin{funcdesc}{dir}{\optional{object}} Without arguments, return the list of names in the current local symbol table. With an argument, attempts to return a list of valid attributes for that object. This information is gleaned from the object's \member{__dict__} attribute, if defined, and from the class or type object. The list is not necessarily complete. If the object is a module object, the list contains the names of the module's attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes. The resulting list is sorted alphabetically. For example: \begin{verbatim} >>> import struct >>> dir() ['__builtins__', '__doc__', '__name__', 'struct'] >>> dir(struct) ['__doc__', '__name__', 'calcsize', 'error', 'pack', 'unpack'] \end{verbatim} \note{Because \function{dir()} is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases.} \end{funcdesc} \begin{funcdesc}{divmod}{a, b} Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as \code{(\var{a} // \var{b}, \var{a} \%{} \var{b})}. For floating point numbers the result is \code{(\var{q}, \var{a} \%{} \var{b})}, where \var{q} is usually \code{math.floor(\var{a} / \var{b})} but may be 1 less than that. In any case \code{\var{q} * \var{b} + \var{a} \%{} \var{b}} is very close to \var{a}, if \code{\var{a} \%{} \var{b}} is non-zero it has the same sign as \var{b}, and \code{0 <= abs(\var{a} \%{} \var{b}) < abs(\var{b})}. \versionchanged[Using \function{divmod()} with complex numbers is deprecated]{2.3} \end{funcdesc} \begin{funcdesc}{enumerate}{iterable} Return an enumerate object. \var{iterable} must be a sequence, an iterator, or some other object which supports iteration. The \method{next()} method of the iterator returned by \function{enumerate()} returns a tuple containing a count (from zero) and the corresponding value obtained from iterating over \var{iterable}. \function{enumerate()} is useful for obtaining an indexed series: \code{(0, seq[0])}, \code{(1, seq[1])}, \code{(2, seq[2])}, \ldots. \versionadded{2.3} \end{funcdesc} \begin{funcdesc}{eval}{expression\optional{, globals\optional{, locals}}} The arguments are a string and optional globals and locals. If provided, \var{globals} must be a dictionary. If provided, \var{locals} can be any mapping object. \versionchanged[formerly \var{locals} was required to be a dictionary]{2.4} The \var{expression} argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the \var{globals} and \var{locals} dictionaries as global and local name space. If the \var{globals} dictionary is present and lacks '__builtins__', the current globals are copied into \var{globals} before \var{expression} is parsed. This means that \var{expression} normally has full access to the standard \refmodule[builtin]{__builtin__} module and restricted environments are propagated. If the \var{locals} dictionary is omitted it defaults to the \var{globals} dictionary. If both dictionaries are omitted, the expression is executed in the environment where \keyword{eval} is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example: \begin{verbatim} >>> x = 1 >>> print eval('x+1') 2 \end{verbatim} This function can also be used to execute arbitrary code objects (such as those created by \function{compile()}). In this case pass a code object instead of a string. The code object must have been compiled passing \code{'eval'} as the \var{kind} argument. Hints: dynamic execution of statements is supported by the \keyword{exec} statement. Execution of statements from a file is supported by the \function{execfile()} function. The \function{globals()} and \function{locals()} functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by \function{eval()} or \function{execfile()}. \end{funcdesc} \begin{funcdesc}{execfile}{filename\optional{, globals\optional{, locals}}} This function is similar to the \keyword{exec} statement, but parses a file instead of a string. It is different from the \keyword{import} statement in that it does not use the module administration --- it reads the file unconditionally and does not create a new module.\footnote{It is used relatively rarely so does not warrant being made into a statement.} The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the \var{globals} and \var{locals} dictionaries as global and local namespace. If provided, \var{locals} can be any mapping object. \versionchanged[formerly \var{locals} was required to be a dictionary]{2.4} If the \var{locals} dictionary is omitted it defaults to the \var{globals} dictionary. If both dictionaries are omitted, the expression is executed in the environment where \function{execfile()} is called. The return value is \code{None}. \warning{The default \var{locals} act as described for function \function{locals()} below: modifications to the default \var{locals} dictionary should not be attempted. Pass an explicit \var{locals} dictionary if you need to see effects of the code on \var{locals} after function \function{execfile()} returns. \function{execfile()} cannot be used reliably to modify a function's locals.} \end{funcdesc} \begin{funcdesc}{file}{filename\optional{, mode\optional{, bufsize}}} Constructor function for the \class{file} type, described further in section~\ref{bltin-file-objects}, ``\ulink{File Objects}{bltin-file-objects.html}''. The constructor's arguments are the same as those of the \function{open()} built-in function described below. When opening a file, it's preferable to use \function{open()} instead of invoking this constructor directly. \class{file} is more suited to type testing (for example, writing \samp{isinstance(f, file)}). \versionadded{2.2} \end{funcdesc} \begin{funcdesc}{filter}{function, iterable} Construct a list from those elements of \var{iterable} for which \var{function} returns true. \var{iterable} may be either a sequence, a container which supports iteration, or an iterator, If \var{iterable} is a string or a tuple, the result also has that type; otherwise it is always a list. If \var{function} is \code{None}, the identity function is assumed, that is, all elements of \var{iterable} that are false are removed. Note that \code{filter(function, \var{iterable})} is equivalent to \code{[item for item in \var{iterable} if function(item)]} if function is not \code{None} and \code{[item for item in \var{iterable} if item]} if function is \code{None}. \end{funcdesc} \begin{funcdesc}{float}{\optional{x}} Convert a string or a number to floating point. If the argument is a string, it must contain a possibly signed decimal or floating point number, possibly embedded in whitespace. Otherwise, the argument may be a plain or long integer or a floating point number, and a floating point number with the same value (within Python's floating point precision) is returned. If no argument is given, returns \code{0.0}. \note{When passing in a string, values for NaN\index{NaN} and Infinity\index{Infinity} may be returned, depending on the underlying C library. The specific set of strings accepted which cause these values to be returned depends entirely on the C library and is known to vary.} \end{funcdesc} \begin{funcdesc}{frozenset}{\optional{iterable}} Return a frozenset object whose elements are taken from \var{iterable}. Frozensets are sets that have no update methods but can be hashed and used as members of other sets or as dictionary keys. The elements of a frozenset must be immutable themselves. To represent sets of sets, the inner sets should also be \class{frozenset} objects. If \var{iterable} is not specified, returns a new empty set, \code{frozenset([])}. \versionadded{2.4} \end{funcdesc} \begin{funcdesc}{getattr}{object, name\optional{, default}} Return the value of the named attributed of \var{object}. \var{name} must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, \code{getattr(x, 'foobar')} is equivalent to \code{x.foobar}. If the named attribute does not exist, \var{default} is returned if provided, otherwise \exception{AttributeError} is raised. \end{funcdesc} \begin{funcdesc}{globals}{} Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called). \end{funcdesc} \begin{funcdesc}{hasattr}{object, name} The arguments are an object and a string. The result is \code{True} if the string is the name of one of the object's attributes, \code{False} if not. (This is implemented by calling \code{getattr(\var{object}, \var{name})} and seeing whether it raises an exception or not.) \end{funcdesc} \begin{funcdesc}{hash}{object} Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0). \end{funcdesc} \begin{funcdesc}{help}{\optional{object}} Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated. \versionadded{2.2} \end{funcdesc} \begin{funcdesc}{hex}{x}