Kaydet (Commit) 8e6c6b26 authored tarafından Fred Drake's avatar Fred Drake

Relocating file to Doc/ref.

üst 64958d59
\documentclass{manual}
\title{Python Reference Manual}
\input{boilerplate}
\makeindex
\begin{document}
\maketitle
\input{copyright}
\begin{abstract}
\noindent
Python is a simple, yet powerful, interpreted programming language
that bridges the gap between C and shell programming, and is thus
ideally suited for ``throw-away programming'' and rapid prototyping.
Its syntax is put together from constructs borrowed from a variety of
other languages; most prominent are influences from ABC, C, Modula-3
and Icon.
The Python interpreter is easily extended with new functions and data
types implemented in C. Python is also suitable as an extension
language for highly customizable C applications such as editors or
window managers.
Python is available for various operating systems, amongst which
several flavors of {\UNIX} (including Linux), the Apple Macintosh O.S.,
MS-DOS, MS-Windows 3.1, Windows NT, and OS/2.
This reference manual describes the syntax and ``core semantics'' of
the language. It is terse, but attempts to be exact and complete.
The semantics of non-essential built-in object types and of the
built-in functions and modules are described in the {\em Python
Library Reference}. For an informal introduction to the language, see
the {\em Python Tutorial}.
\end{abstract}
\tableofcontents
\include{ref1} % Introduction
\include{ref2} % Lexical analysis
\include{ref3} % Data model
\include{ref4} % Execution model
\include{ref5} % Expressions and conditions
\include{ref6} % Simple statements
\include{ref7} % Compound statements
\include{ref8} % Top-level components
\input{ref.ind}
\end{document}
\chapter{Introduction}
This reference manual describes the Python programming language.
It is not intended as a tutorial.
While I am trying to be as precise as possible, I chose to use English
rather than formal specifications for everything except syntax and
lexical analysis. This should make the document more understandable
to the average reader, but will leave room for ambiguities.
Consequently, if you were coming from Mars and tried to re-implement
Python from this document alone, you might have to guess things and in
fact you would probably end up implementing quite a different language.
On the other hand, if you are using
Python and wonder what the precise rules about a particular area of
the language are, you should definitely be able to find them here.
It is dangerous to add too many implementation details to a language
reference document --- the implementation may change, and other
implementations of the same language may work differently. On the
other hand, there is currently only one Python implementation, and
its particular quirks are sometimes worth being mentioned, especially
where the implementation imposes additional limitations. Therefore,
you'll find short ``implementation notes'' sprinkled throughout the
text.
Every Python implementation comes with a number of built-in and
standard modules. These are not documented here, but in the separate
{\em Python Library Reference} document. A few built-in modules are
mentioned when they interact in a significant way with the language
definition.
\section{Notation}
The descriptions of lexical analysis and syntax use a modified BNF
grammar notation. This uses the following style of definition:
\index{BNF}
\index{grammar}
\index{syntax}
\index{notation}
\begin{verbatim}
name: lc_letter (lc_letter | "_")*
lc_letter: "a"..."z"
\end{verbatim}
The first line says that a \verb@name@ is an \verb@lc_letter@ followed by
a sequence of zero or more \verb@lc_letter@s and underscores. An
\verb@lc_letter@ in turn is any of the single characters `a' through `z'.
(This rule is actually adhered to for the names defined in lexical and
grammar rules in this document.)
Each rule begins with a name (which is the name defined by the rule)
and a colon. A vertical bar (\verb@|@) is used to separate
alternatives; it is the least binding operator in this notation. A
star (\verb@*@) means zero or more repetitions of the preceding item;
likewise, a plus (\verb@+@) means one or more repetitions, and a
phrase enclosed in square brackets (\verb@[ ]@) means zero or one
occurrences (in other words, the enclosed phrase is optional). The
\verb@*@ and \verb@+@ operators bind as tightly as possible;
parentheses are used for grouping. Literal strings are enclosed in
quotes. White space is only meaningful to separate tokens.
Rules are normally contained on a single line; rules with many
alternatives may be formatted alternatively with each line after the
first beginning with a vertical bar.
In lexical definitions (as the example above), two more conventions
are used: Two literal characters separated by three dots mean a choice
of any single character in the given (inclusive) range of \ASCII{}
characters. A phrase between angular brackets (\verb@<...>@) gives an
informal description of the symbol defined; e.g. this could be used
to describe the notion of `control character' if needed.
\index{lexical definitions}
\index{ASCII}
Even though the notation used is almost the same, there is a big
difference between the meaning of lexical and syntactic definitions:
a lexical definition operates on the individual characters of the
input source, while a syntax definition operates on the stream of
tokens generated by the lexical analysis. All uses of BNF in the next
chapter (``Lexical Analysis'') are lexical definitions; uses in
subsequent chapters are syntactic definitions.
This diff is collapsed.
This diff is collapsed.
\chapter{Execution model}
\index{execution model}
\section{Code blocks, execution frames, and name spaces} \label{execframes}
\index{code block}
\indexii{execution}{frame}
\index{name space}
A {\em code block} is a piece of Python program text that can be
executed as a unit, such as a module, a class definition or a function
body. Some code blocks (like modules) are executed only once, others
(like function bodies) may be executed many times. Code blocks may
textually contain other code blocks. Code blocks may invoke other
code blocks (that may or may not be textually contained in them) as
part of their execution, e.g. by invoking (calling) a function.
\index{code block}
\indexii{code}{block}
The following are code blocks: A module is a code block. A function
body is a code block. A class definition is a code block. Each
command typed interactively is a separate code block; a script file is
a code block. The string argument passed to the built-in function
\function{eval()} and to the \keyword{exec} statement are code blocks.
And finally, the expression read and evaluated by the built-in
function \function{input()} is a code block.
A code block is executed in an execution frame. An {\em execution
frame} contains some administrative information (used for debugging),
determines where and how execution continues after the code block's
execution has completed, and (perhaps most importantly) defines two
name spaces, the local and the global name space, that affect
execution of the code block.
\indexii{execution}{frame}
A {\em name space} is a mapping from names (identifiers) to objects.
A particular name space may be referenced by more than one execution
frame, and from other places as well. Adding a name to a name space
is called {\em binding} a name (to an object); changing the mapping of
a name is called {\em rebinding}; removing a name is {\em unbinding}.
Name spaces are functionally equivalent to dictionaries.
\index{name space}
\indexii{binding}{name}
\indexii{rebinding}{name}
\indexii{unbinding}{name}
The {\em local name space} of an execution frame determines the default
place where names are defined and searched. The {\em global name
space} determines the place where names listed in \keyword{global}
statements are defined and searched, and where names that are not
explicitly bound in the current code block are searched.
\indexii{local}{name space}
\indexii{global}{name space}
\stindex{global}
Whether a name is local or global in a code block is determined by
static inspection of the source text for the code block: in the
absence of \keyword{global} statements, a name that is bound anywhere in
the code block is local in the entire code block; all other names are
considered global. The \keyword{global} statement forces global
interpretation of selected names throughout the code block. The
following constructs bind names: formal parameters, \keyword{import}
statements, class and function definitions (these bind the class or
function name), and targets that are identifiers if occurring in an
assignment, \keyword{for} loop header, or except clause header.
A target occurring in a \keyword{del} statement is also considered bound
for this purpose (though the actual semantics are to ``unbind'' the
name).
When a global name is not found in the global name space, it is
searched in the list of ``built-in'' names (which is actually the
global name space of the module \module{__builtin__}). When a name is not
found at all, the \exception{NameError} exception is raised.%
\footnote{If the code block contains \keyword{exec} statements or the
construct \samp{from \ldots import *}, the semantics of names not
explicitly mentioned in a {\tt global} statement change subtly: name
lookup first searches the local name space, then the global one, then
the built-in one.}
\refbimodindex{__builtin__}
\stindex{from}
\stindex{exec}
\stindex{global}
\withsubitem{(built-in exception)}{\ttindex{NameError}}
The following table lists the meaning of the local and global name
space for various types of code blocks. The name space for a
particular module is automatically created when the module is first
referenced. Note that in almost all cases, the global name space is
the name space of the containing module --- scopes in Python do not
nest!
\begin{center}
\begin{tabular}{|l|l|l|l|}
\hline
Code block type & Global name space & Local name space & Notes \\
\hline
Module & n.s. for this module & same as global & \\
Script & n.s. for \module{__main__} & same as global & \\
Interactive command & n.s. for \module{__main__} & same as global & \\
Class definition & global n.s. of containing block & new n.s. & \\
Function body & global n.s. of containing block & new n.s. & (2) \\
String passed to \keyword{exec} statement
& global n.s. of containing block
& local n.s. of containing block & (1) \\
String passed to \function{eval()}
& global n.s. of caller & local n.s. of caller & (1) \\
File read by \function{execfile()}
& global n.s. of caller & local n.s. of caller & (1) \\
Expression read by \function{input()}
& global n.s. of caller & local n.s. of caller & \\
\hline
\end{tabular}
\end{center}
\refbimodindex{__main__}
Notes:
\begin{description}
\item[n.s.] means {\em name space}
\item[(1)] The global and local name space for these can be
overridden with optional extra arguments.
\item[(2)] The body of lambda forms (see section \ref{lambda}) is
treated exactly the same as a (nested) function definition. Lambda
forms have their own name space consisting of their formal arguments.
\indexii{lambda}{form}
\end{description}
The built-in functions \function{globals()} and \function{locals()} returns a
dictionary representing the current global and local name space,
respectively. The effect of modifications to this dictionary on the
name space are undefined.%
\footnote{The current implementations return the dictionary actually
used to implement the name space, {\em except} for functions, where
the optimizer may cause the local name space to be implemented
differently, and \function{locals()} returns a read-only dictionary.}
\section{Exceptions}
Exceptions are a means of breaking out of the normal flow of control
of a code block in order to handle errors or other exceptional
conditions. An exception is {\em raised} at the point where the error
is detected; it may be {\em handled} by the surrounding code block or
by any code block that directly or indirectly invoked the code block
where the error occurred.
\index{exception}
\index{raise an exception}
\index{handle an exception}
\index{exception handler}
\index{errors}
\index{error handling}
The Python interpreter raises an exception when it detects an run-time
error (such as division by zero). A Python program can also
explicitly raise an exception with the \keyword{raise} statement.
Exception handlers are specified with the \keyword{try} ... \keyword{except}
statement.
Python uses the ``termination'' model of error handling: an exception
handler can find out what happened and continue execution at an outer
level, but it cannot repair the cause of the error and retry the
failing operation (except by re-entering the the offending piece of
code from the top).
When an exception is not handled at all, the interpreter terminates
execution of the program, or returns to its interactive main loop.
Exceptions are identified by string objects or class instances. Two
different string objects with the same value identify different
exceptions. An exception can be raised with a class instance. Such
exceptions are caught by specifying an except clause that has the
class name (or a base class) as the condition.
When an exception is raised, an object (maybe \code{None}) is passed
as the exception's ``parameter''; this object does not affect the
selection of an exception handler, but is passed to the selected
exception handler as additional information. For exceptions raised
with a class instance, the instance is passed as the ``parameter''.
For example:
\begin{verbatim}
>>> class Error:
... def __init__(self, msg): self.msg = msg
...
>>> class SpecificError(Error): pass
...
>>> try:
... raise SpecificError('broken')
... except Error, obj:
... print obj.msg
...
broken
\end{verbatim}
See also the description of the \keyword{try} and \keyword{raise}
statements.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
\chapter{Top-level components}
The Python interpreter can get its input from a number of sources:
from a script passed to it as standard input or as program argument,
typed in interactively, from a module source file, etc. This chapter
gives the syntax used in these cases.
\index{interpreter}
\section{Complete Python programs}
\index{program}
While a language specification need not prescribe how the language
interpreter is invoked, it is useful to have a notion of a complete
Python program. A complete Python program is executed in a minimally
initialized environment: all built-in and standard modules are
available, but none have been initialized, except for \verb@sys@
(various system services), \verb@__builtin__@ (built-in functions,
exceptions and \verb@None@) and \verb@__main__@. The latter is used
to provide the local and global name space for execution of the
complete program.
\refbimodindex{sys}
\refbimodindex{__main__}
\refbimodindex{__builtin__}
The syntax for a complete Python program is that for file input,
described in the next section.
The interpreter may also be invoked in interactive mode; in this case,
it does not read and execute a complete program but reads and executes
one statement (possibly compound) at a time. The initial environment
is identical to that of a complete program; each statement is executed
in the name space of \verb@__main__@.
\index{interactive mode}
\refbimodindex{__main__}
Under {\UNIX}, a complete program can be passed to the interpreter in
three forms: with the {\bf -c} {\it string} command line option, as a
file passed as the first command line argument, or as standard input.
If the file or standard input is a tty device, the interpreter enters
interactive mode; otherwise, it executes the file as a complete
program.
\index{UNIX}
\index{command line}
\index{standard input}
\section{File input}
All input read from non-interactive files has the same form:
\begin{verbatim}
file_input: (NEWLINE | statement)*
\end{verbatim}
This syntax is used in the following situations:
\begin{itemize}
\item when parsing a complete Python program (from a file or from a string);
\item when parsing a module;
\item when parsing a string passed to the \verb@exec@ statement;
\end{itemize}
\section{Interactive input}
Input in interactive mode is parsed using the following grammar:
\begin{verbatim}
interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE
\end{verbatim}
Note that a (top-level) compound statement must be followed by a blank
line in interactive mode; this is needed to help the parser detect the
end of the input.
\section{Expression input}
\index{input}
There are two forms of expression input. Both ignore leading
whitespace.
The string argument to \verb@eval()@ must have the following form:
\bifuncindex{eval}
\begin{verbatim}
eval_input: condition_list NEWLINE*
\end{verbatim}
The input line read by \verb@input()@ must have the following form:
\bifuncindex{input}
\begin{verbatim}
input_input: condition_list NEWLINE
\end{verbatim}
Note: to read `raw' input line without interpretation, you can use the
built-in function \verb@raw_input()@ or the \verb@readline()@ method
of file objects.
\obindex{file}
\index{input!raw}
\index{raw input}
\bifuncindex{raw_index}
\ttindex{readline}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment