diff options
author | Guido van Rossum <guido@python.org> | 1992-03-06 10:52:59 (GMT) |
---|---|---|
committer | Guido van Rossum <guido@python.org> | 1992-03-06 10:52:59 (GMT) |
commit | b5e1c184be6fd85531ab18d4faf21dbc59515aba (patch) | |
tree | e0e7c6f90b85b086e876141c774e850a046018c2 | |
parent | f08ab0ad158f88f05dd923b129d2397e1882be14 (diff) | |
download | cpython-b5e1c184be6fd85531ab18d4faf21dbc59515aba.zip cpython-b5e1c184be6fd85531ab18d4faf21dbc59515aba.tar.gz cpython-b5e1c184be6fd85531ab18d4faf21dbc59515aba.tar.bz2 |
Completed missing parts. Restructured ch. 3/4 to Data and Execution
model. Added index.
-rw-r--r-- | Doc/ref.tex | 644 | ||||
-rw-r--r-- | Doc/ref/ref.tex | 644 |
2 files changed, 896 insertions, 392 deletions
diff --git a/Doc/ref.tex b/Doc/ref.tex index 823df62..7a9fd5c 100644 --- a/Doc/ref.tex +++ b/Doc/ref.tex @@ -9,6 +9,9 @@ E-mail: {\tt guido@cwi.nl} } +% Tell \index to actually write the .idx file +\makeindex + \begin{document} \pagenumbering{roman} @@ -65,17 +68,19 @@ lexical analysis. This should make the document better 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 be implementing quite a different language. +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 it here. +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 +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. +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 @@ -87,6 +92,10 @@ definition. 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 | "_")* @@ -96,7 +105,7 @@ lc_letter: "a"..."z" 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 syntax and +(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) @@ -119,18 +128,25 @@ 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. +tokens generated by the lexical analysis. All uses of BNF in the next +chapter (``Lexical Analysis'') are lexical definitions; uses in +subsequenc chapter are syntactic definitions. \chapter{Lexical analysis} A Python program is read by a {\em parser}. Input to the parser is a stream of {\em tokens}, generated by the {\em lexical analyzer}. This chapter describes how the lexical analyzer breaks a file into tokens. +\index{lexical analysis} +\index{parser} +\index{token} \section{Line structure} @@ -138,6 +154,9 @@ A Python program is divided in a number of logical lines. The end of a logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). +\index{line structure} +\index{logical line} +\index{NEWLINE token} \subsection{Comments} @@ -145,6 +164,10 @@ A comment starts with a hash character (\verb\#\) that is not part of a string literal, and ends at the end of the physical line. A comment always signifies the end of the logical line. Comments are ignored by the syntax. +\index{comment} +\index{logical line} +\index{physical line} +\index{hash character} \subsection{Line joining} @@ -153,6 +176,9 @@ backslash characters (\verb/\/), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example: +\index{physical line} +\index{line joining} +\index{backslash character} % \begin{verbatim} moth_names = ['Januari', 'Februari', 'Maart', \ @@ -167,22 +193,32 @@ A logical line that contains only spaces, tabs, and possibly a comment, is ignored (i.e., no NEWLINE token is generated), except that during interactive input of statements, an entirely blank logical line terminates a multi-line statement. +\index{blank line} \subsection{Indentation} Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements. +\index{indentation} +\index{whitespace} +\index{leading whitespace} +\index{space} +\index{tab} +\index{grouping} +\index{statement grouping} First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to there is a multiple of -eight (this is intended to be the same rule as used by UNIX). The +eight (this is intended to be the same rule as used by {\UNIX}). The total number of spaces preceding the first non-blank character then determines the line's indentation. Indentation cannot be split over multiple physical lines using backslashes. The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows. +\index{INDENT token} +\index{DEDENT token} Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on @@ -223,11 +259,11 @@ The following example shows various indentation errors: p = perm(l[:i] + l[i+1:]) # error: unexpected indent for x in p: r.append(l[i:i+1] + x) - return r # error: inconsistent indent + return r # error: inconsistent dedent \end{verbatim} (Actually, the first three errors are detected by the parser; only the -last error is found by the lexical analyzer -- the indentation of +last error is found by the lexical analyzer --- the indentation of \verb\return r\ does not match a level popped off the stack.) \section{Other tokens} @@ -240,7 +276,10 @@ forms a legal token, when read from left to right. \section{Identifiers} -Identifiers are described by the following regular expressions: +Identifiers (also referred to as names) are described by the following +lexical definitions: +\index{identifier} +\index{name} \begin{verbatim} identifier: (letter|"_") (letter|digit|"_")* @@ -257,6 +296,8 @@ Identifiers are unlimited in length. Case is significant. The following identifiers are used as reserved words, or {\em keywords} of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here: +\index{keyword} +\index{reserved word} \begin{verbatim} and del for in print @@ -282,9 +323,14 @@ def finally import pass while \section{Literals} +Literals are notations for constant values of some built-in types. +\index{literal} +\index{constant} + \subsection{String literals} -String literals are described by the following regular expressions: +String literals are described by the following lexical definitions: +\index{string literal} \begin{verbatim} stringliteral: "'" stringitem* "'" @@ -292,11 +338,16 @@ stringitem: stringchar | escapeseq stringchar: <any ASCII character except newline or "\" or "'"> escapeseq: "'" <any ASCII character except newline> \end{verbatim} +\index{ASCII} String literals cannot span physical line boundaries. Escape sequences in strings are actually interpreted according to rules simular to those used by Standard C. The recognized escape sequences are: +\index{physical line} +\index{escape sequence} +\index{Standard C} +\index{C} \begin{center} \begin{tabular}{|l|l|} @@ -312,10 +363,11 @@ are: \verb/\t/ & ASCII Horizontal Tab (TAB) \\ \verb/\v/ & ASCII Vertical Tab (VT) \\ \verb/\/{\em ooo} & ASCII character with octal value {\em ooo} \\ -\verb/\x/{em xx...} & ASCII character with hex value {\em xx...} \\ +\verb/\x/{\em xx...} & ASCII character with hex value {\em xx...} \\ \hline \end{tabular} \end{center} +\index{ASCII} In strict compatibility with in Standard C, up to three octal digits are accepted, but an unlimited number of hex digits is taken to be part of @@ -323,19 +375,29 @@ the hex escape (and then the lower 8 bits of the resulting hex number are used in all current implementations...). All unrecognized escape sequences are left in the string unchanged, -i.e., {\em the backslash is left in the string.} (This rule is +i.e., {\em the backslash is left in the string.} (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken. It also helps a great deal for string literals used as regular expressions or -otherwise passed to other modules that do their own escape handling -- -but you may end up quadrupling backslashes that must appear literally.) +otherwise passed to other modules that do their own escape handling.) +\index{unrecognized escape sequence} \subsection{Numeric literals} There are three types of numeric literals: plain integers, long integers, and floating point numbers. - -Integers and long integers are described by the following regular expressions: +\index{number} +\index{numeric literal} +\index{integer literal} +\index{plain integer literal} +\index{long integer literal} +\index{floating point literal} +\index{hexadecimal literal} +\index{octal literal} +\index{decimal literal} + +Integer and long integer literals are described by the following +lexical definitions: \begin{verbatim} longinteger: integer ("l"|"L") @@ -349,23 +411,26 @@ octdigit: "0"..."7" hexdigit: digit|"a"..."f"|"A"..."F" \end{verbatim} -Although both lower case `l'and upper case `L' are allowed as suffix +Although both lower case `l' and upper case `L' are allowed as suffix for long integers, it is strongly recommended to always use `L', since the letter `l' looks too much like the digit `1'. Plain integer decimal literals must be at most $2^{31} - 1$ (i.e., the -largest positive integer, assuming 32-bit arithmetic); octal and -hexadecimal literals may be as large as $2^{32} - 1$. There is no limit +largest positive integer, assuming 32-bit arithmetic); plain octal and +hexadecimal literals may be as large as $2^{32} - 1$, but values +larger than $2^{31} - 1$ are converted to a signed value in the range +$-2^{31} \dots 2^{31} - 1$ by subtracting $2^{32}$. There is no limit for long integer literals. Some examples of plain and long integer literals: \begin{verbatim} 7 2147483647 0177 0x80000000 -3L 79228162514264337593543950336L 0377L 0100000000L +3L 79228162514264337593543950336L 0377L 0x100000000L \end{verbatim} -Floating point numbers are described by the following regular expressions: +Floating point literals are described by the following lexical +definitions: \begin{verbatim} floatnumber: pointfloat | exponentfloat @@ -392,6 +457,7 @@ Note that numeric literals do not include a sign; a phrase like \section{Operators} The following tokens are operators: +\index{operators} \begin{verbatim} + - * / % @@ -406,15 +472,17 @@ spellings of the same operator. The following tokens serve as delimiters or otherwise have a special meaning: +\index{delimiters} \begin{verbatim} ( ) [ ] { } ; , : . ` = \end{verbatim} -The following printing ASCII characters are not used in Python (except -in string literals and in comments). Their occurrence is an -unconditional error: +The following printing ASCII characters are not used in Python. Their +occurrence outside string literals and comments is an unconditional +error: +\index{ASCII} \begin{verbatim} ! @ $ " ? @@ -422,30 +490,44 @@ unconditional error: They may be used by future versions of the language though! -\chapter{Execution model} +\chapter{Data model} \section{Objects, values and types} -I won't try to define rigorously here what an object is, but I'll give -some properties of objects that are important to know about. +{\em Objects} are Python's abstraction for data. All data in a Python +program is represented by objects or by relations between objects. +(In a sense, and in conformance to Von Neumann's model of a +``stored program computer'', code is also represented by objects.) +\index{object} +\index{data} Every object has an identity, a type and a value. An object's {\em -identity} never changes once it has been created; think of it as the -object's address in memory. An object's {\em type} determines the -operations that an object supports (e.g., ``does it have a length?'') -and also defines the ``meaning'' of the object's value. The type also -never changes. The {\em value} of some objects can change; whether -this is possible is a property of its type. +identity} never changes once it has been created; you may think of it +as the object's address in memory. An object's {\em type} is also +unchangeable. It determines the operations that an object supports +(e.g., ``does it have a length?'') and also defines the possible +values for objects of that type. The {\em value} of some objects can +change. Objects whose value can change are said to be {\em mutable}; +objects whose value is unchangeable once they are created are called +{\em immutable}. The type determines an object's (im)mutability. +\index{identity of an object} +\index{value of an object} +\index{type of an object} +\index{mutable object} +\index{immutable object} Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is -allowed to delay garbage collection or omit it altogether -- it is a +allowed to delay garbage collection or omit it altogether --- it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable. (Implementation note: the current implementation uses a reference-counting scheme which collects most objects as soon as they become unreachable, but never collects garbage containing circular references.) +\index{garbage collection} +\index{reference counting} +\index{unreachable object} Note that the use of the implementation's tracing or debugging facilities may keep objects alive that would normally be collectable. @@ -458,13 +540,18 @@ release the external resource, usually a \verb\close\ method. Programs are strongly recommended to always explicitly close such objects. -Some objects contain references to other objects. These references -are part of the object's value; in most cases, when such a -``container'' object is compared to another (of the same type), the -comparison applies to the {\em values} of the referenced objects (not -their identities). - -Types affect almost all aspects of an object's life. Even the meaning +Some objects contain references to other objects; these are called +{\em containers}. Examples of containers are tuples, lists and +dictionaries. The references are part of a container's value. In +most cases, when we talk about the value of a container, we imply the +values, not the identities of the contained objects; however, when we +talk about the (im)mutability of a container, only the identities of +the immediately contained objects are implied. (So, if an immutable +container contains a reference to a mutable object, its value changes +if that mutable object is changed.) +\index{container} + +Types affect almost all aspects of objects' lives. Even the meaning of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable @@ -479,136 +566,30 @@ value one, depending on the implementation, but \verb\c\ and \verb\d\ are guaranteed to refer to two different, unique, newly created empty lists. -\section{Code blocks, execution frames, and name spaces} - -A ``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 block may -textually contain other code blocks. Code blocks may invoke other -code blocks (that aren't textually contained) as part of their -execution. - -Each command typed interactively is a separate code block; a script -file is a code block; the string argument passed to the built-in -functions \verb\eval\ and \verb\exec\ are code blocks; the expression -read and evaluated by the built-in function \verb\input\ is a code -block. - -A code block is executed in an ``execution frame''. An 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'' that affect execution of the code block. - -A 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 ``binding'' a name (to an object); changing the mapping of a -name is called ``rebinding''; removing a name from the name space is -called ``unbinding''. Name spaces are functionally equivalent to -dictionaries (described below). - -The ``local name space'' of an execution frame determines the default -place where names are defined and searched. The ``global name -space'' determines the place where names listed in \verb\global\ -statements are defined and searched, and where names that are not -explicitly bound in the current code block are searched. - -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 \verb\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 \verb\global\ statement forces global -interpretation of selected names throughout the code block. The -following constructs bind names: formal parameters, \verb\import\ -statements, class and function definitions (these bind the class or -function name), and targets that are identifiers if occurring in an -assignment, \verb\for\ loop header, or \verb\except\ clause header. -(A target occurring in a \verb\del\ statement does not bind a name.) - -When a global name is not found in the global name space, it is -searched in the list of ``built-in'' names (this is actually the -global name space of the module \verb\builtin\). When a name is not -found at all, the \verb\NameError\ exception is raised. - -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. - -\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 \verb\__main__\ & same as global & \\ -Interactive command & n.s. for \verb\__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. & \\ -String passed to \verb\exec\ or \verb\eval\ - & global n.s. of caller & local n.s. of caller & (1) \\ -File read by \verb\execfile\ - & global n.s. of caller & local n.s. of caller & (1) \\ -Expression read by \verb\input\ - & global n.s. of caller & local n.s. of caller & \\ -\hline -\end{tabular} -\end{center} - -Notes: -\begin{description} -\item[(1)] The global and local name space for these functions can be -overridden with optional extra arguments. -\end{description} - -\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 ``raised'' at the point where the error -is detected; it may be ``handled'' by the surrounding code block or by any -code block that directly or indirectly invoked the code block where -the error occurred. - -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 \verb\raise\ statement. -Exception handlers are specified with the \verb\try...except\ statement. - -Python uses the ``termination'' model of error handling: a 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. Two different string -objects with the same value identify different exceptions. - -When an exception is raised, an object (maybe \verb\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. - -\chapter{The standard type hierarchy} +\section{The standard type hierarchy} Below is a list of the types that are built into Python. Extension modules written in C can define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational or complex -numbers, lists of efficiently stored integers, etc.). - -Some type descriptions contain a paragraph listing `special -attributes'. These are attributes that provide access to the +numbers, efficientlt stored arrays of integers, etc.). +\index{type} +\index{type hierarchy} +\index{extension module} +\index{C} + +Some of the type descriptions below contain a paragraph listing +`special attributes'. These are attributes that provide access to the implementation and are not intended for general use. Their definition may change in the future. There are also some `generic' special attributes, not listed with the individual objects: \verb\__methods__\ is a list of the method names of a built-in object, if it has any; \verb\__members__\ is a list of the data attribute names of a built-in object, if it has any. +\index{attribute} +\index{special attribute} +\index{generic special attribute} +\ttindex{__methods__} +\ttindex{__members__} \begin{description} @@ -616,6 +597,7 @@ object, if it has any. This type has a single value. There is a single object with this value. This object is accessed through the built-in name \verb\None\. It is returned from functions that don't explicitly return an object. +\ttindex{None} \item[Numbers] These are created by numeric literals and returned as results @@ -623,12 +605,14 @@ by arithmetic operators and arithmetic built-in functions. Numeric objects are immutable; once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers. +\index{number} Python distinguishes between integers and floating point numbers: \begin{description} \item[Integers] These represent elements from the mathematical set of whole numbers. +\index{integer} There are two types of integers: @@ -644,6 +628,7 @@ For the purpose of shift and mask operations, integers are assumed to have a binary, 2's complement notation using 32 or more bits, and hiding no bits from the user (i.e., all $2^{32}$ different bit patterns correspond to different values). +\index{plain integer} \item[Long integers] These represent numbers in an unlimited range, subject to avaiable @@ -651,6 +636,7 @@ These represent numbers in an unlimited range, subject to avaiable a binary representation is assumed, and negative numbers are represented in a variant of 2's complement which gives the illusion of an infinite string of sign bits extending to the left. +\index{long integer} \end{description} % Integers @@ -661,11 +647,14 @@ plain and long integer domains. For any operation except left shift, if it yields a result in the plain integer domain without causing overflow, it will yield the same result in the long integer domain or when using mixed operands. +\index{integer representation} \item[Floating point numbers] These represent machine-level double precision floating point numbers. You are at the mercy of the underlying machine architecture and C implementation for the accepted range and handling of overflow. +\index{floating point number} +\index{C} \end{description} % Numbers @@ -675,11 +664,17 @@ The built-in function \verb\len()\ returns the number of elements of a sequence. When this number is $n$, the index set contains the numbers $0, 1, \ldots, n-1$. Element \verb\i\ of sequence \verb\a\ is selected by \verb\a[i]\. +\index{seqence} +\bifuncindex{len} +\index{index operation} +\index{item selection} +\index{subscription} Sequences also support slicing: \verb\a[i:j]\ selects all elements with index $k$ such that $i < k < j$. When used as an expression, -a slice is a sequence of the same type -- this implies that the +a slice is a sequence of the same type --- this implies that the index set is renumbered so that it starts at 0 again. +\index{slicing} Sequences are distinguished according to their mutability: @@ -691,6 +686,7 @@ created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however the collection of objects directly referenced by an immutable object cannot change.) +\index{immutable sequence} The following types are immutable sequences: @@ -703,37 +699,61 @@ Characters represent (at least) 8-bit bytes. The built-in functions \verb\chr()\ and \verb\ord()\ convert between characters and nonnegative integers representing the byte values. Bytes with the values 0-127 represent the corresponding ASCII values. +The string data type is also used to represent arrays of bytes, e.g., +to hold data read from a file. +\index{string} +\index{character} +\index{byte} +\index{ASCII} +\bifuncindex{chr} +\bifuncindex{ord} (On systems whose native character set is not ASCII, strings may use EBCDIC in their internal representation, provided the functions \verb\chr()\ and \verb\ord()\ implement a mapping between ASCII and -EBCDIC, and string comparisons preserve the ASCII order. +EBCDIC, and string comparison preserves the ASCII order. Or perhaps someone can propose a better rule?) +\index{ASCII} +\index{EBCDIC} +\index{character set} +\index{string comparison} +\bifuncindex{chr} +\bifuncindex{ord} \item[Tuples] The elements of a tuple are arbitrary Python objects. Tuples of two or more elements are formed by comma-separated lists -of expressions. A tuple of one element can be formed by affixing -a comma to an expression (an expression by itself of course does -not create a tuple). An empty tuple can be formed by enclosing -`nothing' in parentheses. +of expressions. A tuple of one element (a `singleton') can be formed +by affixing a comma to an expression (an expression by itself does +not create a tuple, since parentheses must be usable for grouping of +expressions). An empty tuple can be formed by enclosing `nothing' in +parentheses. +\index{tuple} +\index{singleton tuple} +\index{empty tuple} \end{description} % Immutable sequences \item[Mutable sequences] -Mutable sequences can be changed after they are created. -The subscript and slice notations can be used as the target -of assignment and \verb\del\ (delete) statements. +Mutable sequences can be changed after they are created. The +subscription and slicing notations can be used as the target of +assignment and \verb\del\ (delete) statements. +\index{mutable sequece} +\index{assignment statement} +\kwindex{del} +\index{subscription} +\index{slicing} There is currently a single mutable sequence type: \begin{description} \item[Lists] -The elements of a list are arbitrary Python objects. -Lists are formed by placing a comma-separated list of expressions -in square brackets. (Note that there are no special cases for lists -of length 0 or 1.) +The elements of a list are arbitrary Python objects. Lists are formed +by placing a comma-separated list of expressions in square brackets. +(Note that there are no special cases needed to form lists of length 0 +or 1.) +\index{list} \end{description} % Mutable sequences @@ -746,6 +766,9 @@ by \verb\k\ from the mapping \verb\a\; this can be used in expressions and as the target of assignments or \verb\del\ statements. The built-in function \verb\len()\ returns the number of elements in a mapping. +\bifuncindex{len} +\index{subscription} +\index{mapping} There is currently a single mapping type: @@ -756,26 +779,35 @@ These represent finite sets of objects indexed by strings. Dictionaries are created by the \verb\{...}\ notation (see section \ref{dict}). (Implementation note: the strings used for indexing must not contain null bytes.) +\index{dictionary} \end{description} % Mapping types \item[Callable types] -These are the types to which the function call operation (written as -\verb\function(argument, argument, ...)\) can be applied: +These are the types to which the function call (invocation) operation, +written as \verb\function(argument, argument, ...)\, can be applied: +\index{callable type} +\indexii{function}{call} +\index{invocation} \begin{description} \item[User-defined functions] -A user-defined function is created by a function definition (see -section \ref{function}). It should be called with an argument list -containing the same number of items as the function's formal parameter -list. +A user-defined function object is created by a function definition +(see section \ref{function}). It should be called with an argument +list containing the same number of items as the function's formal +parameter list. +\indexii{user-defined}{function} +\index{function object} Special read-only attributes: \verb\func_code\ is the code object representing the compiled function body, and \verb\func_globals\ is (a reference to) the dictionary that holds the function's global -variables -- it implements the global name space of the module in +variables --- it implements the global name space of the module in which the function was defined. +\ttindex{func_code} +\ttindex{func_globals} +\indexii{global}{name space} \item[User-defined methods] A user-defined method (a.k.a. {\tt object closure}) is a pair of a @@ -784,28 +816,35 @@ called with an argument list containing one item less than the number of items in the function's formal parameter list. When called, the class instance becomes the first argument, and the call arguments are shifted one to the right. +\indexii{object}{closure} +indexii{user-defined}{method} Special read-only attributes: \verb\im_self\ is the class instance object, \verb\im_func\ is the function object. +\ttindex{im_func} +\ttindex{im_self} \item[Built-in functions] A built-in function object is a wrapper around a C function. Examples of built-in functions are \verb\len\ and \verb\math.sin\. There are no special attributes. The number and type of the arguments are determined by the C function. +\index{C} \item[Built-in methods] This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is \verb\list.append\ if \verb\list\ is a list object. +\indexii{built-in}{method} \item[Classes] Class objects are described below. When a class object is called as a parameterless function, a new class instance (also described below) is created and returned. The class's initialization function is not -called -- this is the responsibility of the caller. It is illegal to +called --- this is the responsibility of the caller. It is illegal to call a class object with one or more arguments. +\index{class} \end{description} @@ -818,11 +857,16 @@ Module attribute references are translated to lookups in this dictionary. A module object does not contain the code object used to initialize the module (since it isn't needed once the initialization is done). +\stindex{import} +\index{module} Attribute assignment update the module's name space dictionary. Special read-only attributes: \verb\__dict__\ yields the module's name -space as a dictionary object; \verb\__name__\ yields the module's name. +space as a dictionary object; \verb\__name__\ yields the module's name +as a string object. +\ttindex{__dict__} +\ttindex{__name__} \item[Classes] Class objects are created by class definitions (see section @@ -832,9 +876,14 @@ lookups in this dictionary. When an attribute name is not found there, the attribute search continues in the base classes. The search is depth-first, left-to-right in the order of their occurrence in the base class list. +\index{class} +\index{container} +\index{dictionary} +\indexii{class}{attribute} -Attribute assignments update the class's dictionary, never the +Class attribute assignments update the class's dictionary, never the dictionary of a base class. +\indexiii{class}{attribute}{assignment} A class can be called as a parameterless function to yield a class instance (see above). @@ -843,6 +892,8 @@ Special read-only attributes: \verb\__dict__\ yields te dictionary containing the class's name space; \verb\__bases__\ yields a tuple (possibly empty or a singleton) containing the base classes, in the order of their occurrence in the base class list. +\ttindex{__dict__} +\ttindex{__bases__} \item[Class instances] A class instance is created by calling a class object as a @@ -852,11 +903,16 @@ there, and the instance's class has an attribute by that name, and that class attribute is a user-defined function (and in no other cases), the instance attribute reference yields a user-defined method object (see above) constructed from the instance and the function. +\indexii{class}{instance} +\indexii{class instance}{attribute} Attribute assignments update the instance's dictionary. +\indexiii{class instance}{attribute}{assignment} Special read-only attributes: \verb\__dict__\ yields the attribute dictionary; \verb\__class__\ yields the instance's class. +\ttindex{__dict__} +\ttindex{__class__} \item[Files] A file object represents an open file. (It is a wrapper around a C @@ -867,11 +923,21 @@ the \verb\makefile\ method of socket objects. \verb\sys.stdin\, the the interpreter's standard input, output and error streams. See the Python Library Reference for methods of file objects and other details. +\index{file} +\index{C} +\index{stdio} +\bifuncindex{open} +\bifuncindex{popen} +\bifuncindex{makefile} +\ttindex{stdin} +\ttindex{stdout} +\ttindex{stderr} \item[Internal types] A few types used internally by the interpreter are exposed to the user. Their definition may change with future versions of the interpreter, but they are mentioned here for completeness. +\index{internal type} \begin{description} @@ -881,6 +947,7 @@ object and a function object is that the function object contains an explicit reference to the function's context (the module in which it was defined) which a code object contains no context. There is no way to execute a bare code object. +\index{code object} Special read-only attributes: \verb\co_code\ is a string representing the sequence of instructions; \verb\co_consts\ is a list of literals @@ -889,10 +956,15 @@ the code; \verb\co_filename\ is the filename from which the code was compiled. (To find out the line numbers, you would have to decode the instructions; the standard library module \verb\dis\ contains an example of how to do this.) +\ttindex{co_code} +\ttindex{co_consts} +\ttindex{co_names} +\ttindex{co_filename} \item[Frame objects] Frame objects represent execution frames. They may occur in traceback objects (see below). +\index{frame object} Special read-only attributes: \verb\f_back\ is to the previous stack frame (towards the caller), or \verb\None\ if this is the bottom @@ -902,6 +974,12 @@ variables; \verb\f_locals\ is used for local variables; \verb\f_lineno\ gives the line number and \verb\f_lasti\ gives the precise instruction (this is an index into the instruction string of the code object). +\ttindex{f_back} +\ttindex{f_code} +\ttindex{f_globals} +\ttindex{f_locals} +\ttindex{f_lineno} +\ttindex{f_lasti} \item[Traceback objects] Traceback objects represent a stack trace of an exception. A @@ -912,8 +990,14 @@ traceback. When an exception handler is entered, the stack trace is made available to the program as \verb\sys.exc_traceback\. When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is -interactive, it is made available to the user as +interactive, it is also made available to the user as \verb\sys.last_traceback\. +\index{traceback object} +\indexii{stack}{trace} +\index{exception handler} +\index{execution stack} +\ttindex{exc_traceback} +\ttindex{last_traceback} Special read-only attributes: \verb\tb_next\ is the next level in the stack trace (towards the frame where the exception occurred), or @@ -924,15 +1008,164 @@ precise instruction. The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a \verb\try\ statement with no matching \verb\except\ clause or with a \verb\finally\ clause. +\ttindex{tb_next} +\ttindex{tb_frame} +\ttindex{tb_lineno} +\ttindex{tb_lasti} +\stindex{try} \end{description} % Internal types \end{description} % Types +\chapter{Execution model} + +\section{Code blocks, execution frames, and name spaces} + +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 block 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} + +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 functions +\verb\eval\ and \verb\exec\ are code blocks. And finally, the +expression read and evaluated by the built-in function \verb\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. +\index{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 \verb\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 \verb\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 \verb\global\ statement forces global +interpretation of selected names throughout the code block. The +following constructs bind names: formal parameters, \verb\import\ +statements, class and function definitions (these bind the class or +function name), and targets that are identifiers if occurring in an +assignment, \verb\for\ loop header, or \verb\except\ clause header. +(A target occurring in a \verb\del\ statement does not bind a 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 \verb\builtin\). When a name is not +found at all, the \verb\NameError\ exception is raised. + +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. + +\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 \verb\__main__\ & same as global & \\ +Interactive command & n.s. for \verb\__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. & \\ +String passed to \verb\exec\ or \verb\eval\ + & global n.s. of caller & local n.s. of caller & (1) \\ +File read by \verb\execfile\ + & global n.s. of caller & local n.s. of caller & (1) \\ +Expression read by \verb\input\ + & global n.s. of caller & local n.s. of caller & \\ +\hline +\end{tabular} +\end{center} + +Notes: + +\begin{description} + +\item[n.s.] means {\em name space} + +\item[(1)] The global and local name space for these functions can be +overridden with optional extra arguments. + +\end{description} + +\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 \verb\raise\ statement. +Exception handlers are specified with the \verb\try...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. Two different string +objects with the same value identify different exceptions. + +When an exception is raised, an object (maybe \verb\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. + +See also the description of the \verb\try\ and \verb\raise\ +statements. + \chapter{Expressions and conditions} -From now on, extended BNF notation will be used to describe syntax, -not lexical analysis. +In this and the following chapters, extended BNF notation will be used +to describe syntax, not lexical analysis. +\index{BNF} This chapter explains the meaning of the elements of expressions and conditions. Conditions are a superset of expressions, and a condition @@ -942,7 +1175,7 @@ instead of conditions is in expression statements and on the right-hand side of assignments; this catches some nasty bugs like accedentally writing \verb\x == 1\ instead of \verb\x = 1\. -The comma has several roles in Python's syntax. It is usually an +The comma plays several roles in Python's syntax. It is usually an operator with a lower precedence than all others, but occasionally serves other purposes as well; e.g., it separates function arguments, is used in list and dictionary constructors, and has special semantics @@ -1037,7 +1270,7 @@ tuples are immutable, the rules for literals apply here. (Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which -parentheses {\em are} required -- allowing unparenthesized ``nothing'' +parentheses {\em are} required --- allowing unparenthesized ``nothing'' in expressions would causes ambiguities and allow common typos to pass uncaught.) @@ -1632,7 +1865,7 @@ messages.) pass_stmt: "pass" \end{verbatim} -\verb\pass\ is a null operation -- when it is executed, nothing +\verb\pass\ is a null operation --- when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example: @@ -2035,12 +2268,12 @@ When a \verb\return\ or \verb\break\ statement is executed in the \verb\try\ suite of a \verb\try...finally\ statement, the \verb\finally\ clause is also executed `on the way out'. A \verb\continue\ statement is illegal in the \verb\try\ clause (the -reason is a problem with the current implementation -- this +reason is a problem with the current implementation --- this restriction may be lifted in the future). \section{Function definitions} \label{function} -XXX +A function definition defines a function: \begin{verbatim} funcdef: "def" identifier "(" [parameter_list] ")" ":" suite @@ -2048,18 +2281,35 @@ parameter_list: parameter ("," parameter)* parameter: identifier | "(" parameter_list ")" \end{verbatim} -XXX +A function definition is an executable statement. Its execution binds +the function name in the current local name space to a function object +(a wrapper around the executable code for the function). This +function object contains a reference to the current global name space +as the global name space to be used when the function is called. + +The function definition does not execute the function body; this gets +executed only when the function is called. Function call semantics +are described elsewhere (see XXX). \section{Class definitions} \label{class} -XXX +A class definition defines a class: \begin{verbatim} classdef: "class" identifier [inheritance] ":" suite inheritance: "(" condition_list ")" \end{verbatim} -XXX +A class definition is an executable statement. It first executes the +inheritance list, if present. The class's suite is executed in a new +execution frame, using a newly created local name space and the +original global name space. (Usually, the suite contains only +function definitions.) When the class's suite finishes execution, its +execution frame is discarded but its local name space is saved. A +class object (see XXX) is created using the inheritance list for the +base classes and the saved local name space for the attribute +dictionary. The class name is then bound to this class object in the +original local name space. \section{P.M.} @@ -2067,4 +2317,6 @@ XXX Syntax for scripts, modules XXX Syntax for interactive input, eval, exec, execfile, input XXX New definition of expressions (as conditions) +\input{ref.ind} % The index + \end{document} diff --git a/Doc/ref/ref.tex b/Doc/ref/ref.tex index 823df62..7a9fd5c 100644 --- a/Doc/ref/ref.tex +++ b/Doc/ref/ref.tex @@ -9,6 +9,9 @@ E-mail: {\tt guido@cwi.nl} } +% Tell \index to actually write the .idx file +\makeindex + \begin{document} \pagenumbering{roman} @@ -65,17 +68,19 @@ lexical analysis. This should make the document better 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 be implementing quite a different language. +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 it here. +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 +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. +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 @@ -87,6 +92,10 @@ definition. 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 | "_")* @@ -96,7 +105,7 @@ lc_letter: "a"..."z" 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 syntax and +(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) @@ -119,18 +128,25 @@ 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. +tokens generated by the lexical analysis. All uses of BNF in the next +chapter (``Lexical Analysis'') are lexical definitions; uses in +subsequenc chapter are syntactic definitions. \chapter{Lexical analysis} A Python program is read by a {\em parser}. Input to the parser is a stream of {\em tokens}, generated by the {\em lexical analyzer}. This chapter describes how the lexical analyzer breaks a file into tokens. +\index{lexical analysis} +\index{parser} +\index{token} \section{Line structure} @@ -138,6 +154,9 @@ A Python program is divided in a number of logical lines. The end of a logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). +\index{line structure} +\index{logical line} +\index{NEWLINE token} \subsection{Comments} @@ -145,6 +164,10 @@ A comment starts with a hash character (\verb\#\) that is not part of a string literal, and ends at the end of the physical line. A comment always signifies the end of the logical line. Comments are ignored by the syntax. +\index{comment} +\index{logical line} +\index{physical line} +\index{hash character} \subsection{Line joining} @@ -153,6 +176,9 @@ backslash characters (\verb/\/), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example: +\index{physical line} +\index{line joining} +\index{backslash character} % \begin{verbatim} moth_names = ['Januari', 'Februari', 'Maart', \ @@ -167,22 +193,32 @@ A logical line that contains only spaces, tabs, and possibly a comment, is ignored (i.e., no NEWLINE token is generated), except that during interactive input of statements, an entirely blank logical line terminates a multi-line statement. +\index{blank line} \subsection{Indentation} Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements. +\index{indentation} +\index{whitespace} +\index{leading whitespace} +\index{space} +\index{tab} +\index{grouping} +\index{statement grouping} First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to there is a multiple of -eight (this is intended to be the same rule as used by UNIX). The +eight (this is intended to be the same rule as used by {\UNIX}). The total number of spaces preceding the first non-blank character then determines the line's indentation. Indentation cannot be split over multiple physical lines using backslashes. The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows. +\index{INDENT token} +\index{DEDENT token} Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on @@ -223,11 +259,11 @@ The following example shows various indentation errors: p = perm(l[:i] + l[i+1:]) # error: unexpected indent for x in p: r.append(l[i:i+1] + x) - return r # error: inconsistent indent + return r # error: inconsistent dedent \end{verbatim} (Actually, the first three errors are detected by the parser; only the -last error is found by the lexical analyzer -- the indentation of +last error is found by the lexical analyzer --- the indentation of \verb\return r\ does not match a level popped off the stack.) \section{Other tokens} @@ -240,7 +276,10 @@ forms a legal token, when read from left to right. \section{Identifiers} -Identifiers are described by the following regular expressions: +Identifiers (also referred to as names) are described by the following +lexical definitions: +\index{identifier} +\index{name} \begin{verbatim} identifier: (letter|"_") (letter|digit|"_")* @@ -257,6 +296,8 @@ Identifiers are unlimited in length. Case is significant. The following identifiers are used as reserved words, or {\em keywords} of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here: +\index{keyword} +\index{reserved word} \begin{verbatim} and del for in print @@ -282,9 +323,14 @@ def finally import pass while \section{Literals} +Literals are notations for constant values of some built-in types. +\index{literal} +\index{constant} + \subsection{String literals} -String literals are described by the following regular expressions: +String literals are described by the following lexical definitions: +\index{string literal} \begin{verbatim} stringliteral: "'" stringitem* "'" @@ -292,11 +338,16 @@ stringitem: stringchar | escapeseq stringchar: <any ASCII character except newline or "\" or "'"> escapeseq: "'" <any ASCII character except newline> \end{verbatim} +\index{ASCII} String literals cannot span physical line boundaries. Escape sequences in strings are actually interpreted according to rules simular to those used by Standard C. The recognized escape sequences are: +\index{physical line} +\index{escape sequence} +\index{Standard C} +\index{C} \begin{center} \begin{tabular}{|l|l|} @@ -312,10 +363,11 @@ are: \verb/\t/ & ASCII Horizontal Tab (TAB) \\ \verb/\v/ & ASCII Vertical Tab (VT) \\ \verb/\/{\em ooo} & ASCII character with octal value {\em ooo} \\ -\verb/\x/{em xx...} & ASCII character with hex value {\em xx...} \\ +\verb/\x/{\em xx...} & ASCII character with hex value {\em xx...} \\ \hline \end{tabular} \end{center} +\index{ASCII} In strict compatibility with in Standard C, up to three octal digits are accepted, but an unlimited number of hex digits is taken to be part of @@ -323,19 +375,29 @@ the hex escape (and then the lower 8 bits of the resulting hex number are used in all current implementations...). All unrecognized escape sequences are left in the string unchanged, -i.e., {\em the backslash is left in the string.} (This rule is +i.e., {\em the backslash is left in the string.} (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken. It also helps a great deal for string literals used as regular expressions or -otherwise passed to other modules that do their own escape handling -- -but you may end up quadrupling backslashes that must appear literally.) +otherwise passed to other modules that do their own escape handling.) +\index{unrecognized escape sequence} \subsection{Numeric literals} There are three types of numeric literals: plain integers, long integers, and floating point numbers. - -Integers and long integers are described by the following regular expressions: +\index{number} +\index{numeric literal} +\index{integer literal} +\index{plain integer literal} +\index{long integer literal} +\index{floating point literal} +\index{hexadecimal literal} +\index{octal literal} +\index{decimal literal} + +Integer and long integer literals are described by the following +lexical definitions: \begin{verbatim} longinteger: integer ("l"|"L") @@ -349,23 +411,26 @@ octdigit: "0"..."7" hexdigit: digit|"a"..."f"|"A"..."F" \end{verbatim} -Although both lower case `l'and upper case `L' are allowed as suffix +Although both lower case `l' and upper case `L' are allowed as suffix for long integers, it is strongly recommended to always use `L', since the letter `l' looks too much like the digit `1'. Plain integer decimal literals must be at most $2^{31} - 1$ (i.e., the -largest positive integer, assuming 32-bit arithmetic); octal and -hexadecimal literals may be as large as $2^{32} - 1$. There is no limit +largest positive integer, assuming 32-bit arithmetic); plain octal and +hexadecimal literals may be as large as $2^{32} - 1$, but values +larger than $2^{31} - 1$ are converted to a signed value in the range +$-2^{31} \dots 2^{31} - 1$ by subtracting $2^{32}$. There is no limit for long integer literals. Some examples of plain and long integer literals: \begin{verbatim} 7 2147483647 0177 0x80000000 -3L 79228162514264337593543950336L 0377L 0100000000L +3L 79228162514264337593543950336L 0377L 0x100000000L \end{verbatim} -Floating point numbers are described by the following regular expressions: +Floating point literals are described by the following lexical +definitions: \begin{verbatim} floatnumber: pointfloat | exponentfloat @@ -392,6 +457,7 @@ Note that numeric literals do not include a sign; a phrase like \section{Operators} The following tokens are operators: +\index{operators} \begin{verbatim} + - * / % @@ -406,15 +472,17 @@ spellings of the same operator. The following tokens serve as delimiters or otherwise have a special meaning: +\index{delimiters} \begin{verbatim} ( ) [ ] { } ; , : . ` = \end{verbatim} -The following printing ASCII characters are not used in Python (except -in string literals and in comments). Their occurrence is an -unconditional error: +The following printing ASCII characters are not used in Python. Their +occurrence outside string literals and comments is an unconditional +error: +\index{ASCII} \begin{verbatim} ! @ $ " ? @@ -422,30 +490,44 @@ unconditional error: They may be used by future versions of the language though! -\chapter{Execution model} +\chapter{Data model} \section{Objects, values and types} -I won't try to define rigorously here what an object is, but I'll give -some properties of objects that are important to know about. +{\em Objects} are Python's abstraction for data. All data in a Python +program is represented by objects or by relations between objects. +(In a sense, and in conformance to Von Neumann's model of a +``stored program computer'', code is also represented by objects.) +\index{object} +\index{data} Every object has an identity, a type and a value. An object's {\em -identity} never changes once it has been created; think of it as the -object's address in memory. An object's {\em type} determines the -operations that an object supports (e.g., ``does it have a length?'') -and also defines the ``meaning'' of the object's value. The type also -never changes. The {\em value} of some objects can change; whether -this is possible is a property of its type. +identity} never changes once it has been created; you may think of it +as the object's address in memory. An object's {\em type} is also +unchangeable. It determines the operations that an object supports +(e.g., ``does it have a length?'') and also defines the possible +values for objects of that type. The {\em value} of some objects can +change. Objects whose value can change are said to be {\em mutable}; +objects whose value is unchangeable once they are created are called +{\em immutable}. The type determines an object's (im)mutability. +\index{identity of an object} +\index{value of an object} +\index{type of an object} +\index{mutable object} +\index{immutable object} Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is -allowed to delay garbage collection or omit it altogether -- it is a +allowed to delay garbage collection or omit it altogether --- it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable. (Implementation note: the current implementation uses a reference-counting scheme which collects most objects as soon as they become unreachable, but never collects garbage containing circular references.) +\index{garbage collection} +\index{reference counting} +\index{unreachable object} Note that the use of the implementation's tracing or debugging facilities may keep objects alive that would normally be collectable. @@ -458,13 +540,18 @@ release the external resource, usually a \verb\close\ method. Programs are strongly recommended to always explicitly close such objects. -Some objects contain references to other objects. These references -are part of the object's value; in most cases, when such a -``container'' object is compared to another (of the same type), the -comparison applies to the {\em values} of the referenced objects (not -their identities). - -Types affect almost all aspects of an object's life. Even the meaning +Some objects contain references to other objects; these are called +{\em containers}. Examples of containers are tuples, lists and +dictionaries. The references are part of a container's value. In +most cases, when we talk about the value of a container, we imply the +values, not the identities of the contained objects; however, when we +talk about the (im)mutability of a container, only the identities of +the immediately contained objects are implied. (So, if an immutable +container contains a reference to a mutable object, its value changes +if that mutable object is changed.) +\index{container} + +Types affect almost all aspects of objects' lives. Even the meaning of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable @@ -479,136 +566,30 @@ value one, depending on the implementation, but \verb\c\ and \verb\d\ are guaranteed to refer to two different, unique, newly created empty lists. -\section{Code blocks, execution frames, and name spaces} - -A ``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 block may -textually contain other code blocks. Code blocks may invoke other -code blocks (that aren't textually contained) as part of their -execution. - -Each command typed interactively is a separate code block; a script -file is a code block; the string argument passed to the built-in -functions \verb\eval\ and \verb\exec\ are code blocks; the expression -read and evaluated by the built-in function \verb\input\ is a code -block. - -A code block is executed in an ``execution frame''. An 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'' that affect execution of the code block. - -A 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 ``binding'' a name (to an object); changing the mapping of a -name is called ``rebinding''; removing a name from the name space is -called ``unbinding''. Name spaces are functionally equivalent to -dictionaries (described below). - -The ``local name space'' of an execution frame determines the default -place where names are defined and searched. The ``global name -space'' determines the place where names listed in \verb\global\ -statements are defined and searched, and where names that are not -explicitly bound in the current code block are searched. - -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 \verb\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 \verb\global\ statement forces global -interpretation of selected names throughout the code block. The -following constructs bind names: formal parameters, \verb\import\ -statements, class and function definitions (these bind the class or -function name), and targets that are identifiers if occurring in an -assignment, \verb\for\ loop header, or \verb\except\ clause header. -(A target occurring in a \verb\del\ statement does not bind a name.) - -When a global name is not found in the global name space, it is -searched in the list of ``built-in'' names (this is actually the -global name space of the module \verb\builtin\). When a name is not -found at all, the \verb\NameError\ exception is raised. - -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. - -\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 \verb\__main__\ & same as global & \\ -Interactive command & n.s. for \verb\__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. & \\ -String passed to \verb\exec\ or \verb\eval\ - & global n.s. of caller & local n.s. of caller & (1) \\ -File read by \verb\execfile\ - & global n.s. of caller & local n.s. of caller & (1) \\ -Expression read by \verb\input\ - & global n.s. of caller & local n.s. of caller & \\ -\hline -\end{tabular} -\end{center} - -Notes: -\begin{description} -\item[(1)] The global and local name space for these functions can be -overridden with optional extra arguments. -\end{description} - -\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 ``raised'' at the point where the error -is detected; it may be ``handled'' by the surrounding code block or by any -code block that directly or indirectly invoked the code block where -the error occurred. - -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 \verb\raise\ statement. -Exception handlers are specified with the \verb\try...except\ statement. - -Python uses the ``termination'' model of error handling: a 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. Two different string -objects with the same value identify different exceptions. - -When an exception is raised, an object (maybe \verb\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. - -\chapter{The standard type hierarchy} +\section{The standard type hierarchy} Below is a list of the types that are built into Python. Extension modules written in C can define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational or complex -numbers, lists of efficiently stored integers, etc.). - -Some type descriptions contain a paragraph listing `special -attributes'. These are attributes that provide access to the +numbers, efficientlt stored arrays of integers, etc.). +\index{type} +\index{type hierarchy} +\index{extension module} +\index{C} + +Some of the type descriptions below contain a paragraph listing +`special attributes'. These are attributes that provide access to the implementation and are not intended for general use. Their definition may change in the future. There are also some `generic' special attributes, not listed with the individual objects: \verb\__methods__\ is a list of the method names of a built-in object, if it has any; \verb\__members__\ is a list of the data attribute names of a built-in object, if it has any. +\index{attribute} +\index{special attribute} +\index{generic special attribute} +\ttindex{__methods__} +\ttindex{__members__} \begin{description} @@ -616,6 +597,7 @@ object, if it has any. This type has a single value. There is a single object with this value. This object is accessed through the built-in name \verb\None\. It is returned from functions that don't explicitly return an object. +\ttindex{None} \item[Numbers] These are created by numeric literals and returned as results @@ -623,12 +605,14 @@ by arithmetic operators and arithmetic built-in functions. Numeric objects are immutable; once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers. +\index{number} Python distinguishes between integers and floating point numbers: \begin{description} \item[Integers] These represent elements from the mathematical set of whole numbers. +\index{integer} There are two types of integers: @@ -644,6 +628,7 @@ For the purpose of shift and mask operations, integers are assumed to have a binary, 2's complement notation using 32 or more bits, and hiding no bits from the user (i.e., all $2^{32}$ different bit patterns correspond to different values). +\index{plain integer} \item[Long integers] These represent numbers in an unlimited range, subject to avaiable @@ -651,6 +636,7 @@ These represent numbers in an unlimited range, subject to avaiable a binary representation is assumed, and negative numbers are represented in a variant of 2's complement which gives the illusion of an infinite string of sign bits extending to the left. +\index{long integer} \end{description} % Integers @@ -661,11 +647,14 @@ plain and long integer domains. For any operation except left shift, if it yields a result in the plain integer domain without causing overflow, it will yield the same result in the long integer domain or when using mixed operands. +\index{integer representation} \item[Floating point numbers] These represent machine-level double precision floating point numbers. You are at the mercy of the underlying machine architecture and C implementation for the accepted range and handling of overflow. +\index{floating point number} +\index{C} \end{description} % Numbers @@ -675,11 +664,17 @@ The built-in function \verb\len()\ returns the number of elements of a sequence. When this number is $n$, the index set contains the numbers $0, 1, \ldots, n-1$. Element \verb\i\ of sequence \verb\a\ is selected by \verb\a[i]\. +\index{seqence} +\bifuncindex{len} +\index{index operation} +\index{item selection} +\index{subscription} Sequences also support slicing: \verb\a[i:j]\ selects all elements with index $k$ such that $i < k < j$. When used as an expression, -a slice is a sequence of the same type -- this implies that the +a slice is a sequence of the same type --- this implies that the index set is renumbered so that it starts at 0 again. +\index{slicing} Sequences are distinguished according to their mutability: @@ -691,6 +686,7 @@ created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however the collection of objects directly referenced by an immutable object cannot change.) +\index{immutable sequence} The following types are immutable sequences: @@ -703,37 +699,61 @@ Characters represent (at least) 8-bit bytes. The built-in functions \verb\chr()\ and \verb\ord()\ convert between characters and nonnegative integers representing the byte values. Bytes with the values 0-127 represent the corresponding ASCII values. +The string data type is also used to represent arrays of bytes, e.g., +to hold data read from a file. +\index{string} +\index{character} +\index{byte} +\index{ASCII} +\bifuncindex{chr} +\bifuncindex{ord} (On systems whose native character set is not ASCII, strings may use EBCDIC in their internal representation, provided the functions \verb\chr()\ and \verb\ord()\ implement a mapping between ASCII and -EBCDIC, and string comparisons preserve the ASCII order. +EBCDIC, and string comparison preserves the ASCII order. Or perhaps someone can propose a better rule?) +\index{ASCII} +\index{EBCDIC} +\index{character set} +\index{string comparison} +\bifuncindex{chr} +\bifuncindex{ord} \item[Tuples] The elements of a tuple are arbitrary Python objects. Tuples of two or more elements are formed by comma-separated lists -of expressions. A tuple of one element can be formed by affixing -a comma to an expression (an expression by itself of course does -not create a tuple). An empty tuple can be formed by enclosing -`nothing' in parentheses. +of expressions. A tuple of one element (a `singleton') can be formed +by affixing a comma to an expression (an expression by itself does +not create a tuple, since parentheses must be usable for grouping of +expressions). An empty tuple can be formed by enclosing `nothing' in +parentheses. +\index{tuple} +\index{singleton tuple} +\index{empty tuple} \end{description} % Immutable sequences \item[Mutable sequences] -Mutable sequences can be changed after they are created. -The subscript and slice notations can be used as the target -of assignment and \verb\del\ (delete) statements. +Mutable sequences can be changed after they are created. The +subscription and slicing notations can be used as the target of +assignment and \verb\del\ (delete) statements. +\index{mutable sequece} +\index{assignment statement} +\kwindex{del} +\index{subscription} +\index{slicing} There is currently a single mutable sequence type: \begin{description} \item[Lists] -The elements of a list are arbitrary Python objects. -Lists are formed by placing a comma-separated list of expressions -in square brackets. (Note that there are no special cases for lists -of length 0 or 1.) +The elements of a list are arbitrary Python objects. Lists are formed +by placing a comma-separated list of expressions in square brackets. +(Note that there are no special cases needed to form lists of length 0 +or 1.) +\index{list} \end{description} % Mutable sequences @@ -746,6 +766,9 @@ by \verb\k\ from the mapping \verb\a\; this can be used in expressions and as the target of assignments or \verb\del\ statements. The built-in function \verb\len()\ returns the number of elements in a mapping. +\bifuncindex{len} +\index{subscription} +\index{mapping} There is currently a single mapping type: @@ -756,26 +779,35 @@ These represent finite sets of objects indexed by strings. Dictionaries are created by the \verb\{...}\ notation (see section \ref{dict}). (Implementation note: the strings used for indexing must not contain null bytes.) +\index{dictionary} \end{description} % Mapping types \item[Callable types] -These are the types to which the function call operation (written as -\verb\function(argument, argument, ...)\) can be applied: +These are the types to which the function call (invocation) operation, +written as \verb\function(argument, argument, ...)\, can be applied: +\index{callable type} +\indexii{function}{call} +\index{invocation} \begin{description} \item[User-defined functions] -A user-defined function is created by a function definition (see -section \ref{function}). It should be called with an argument list -containing the same number of items as the function's formal parameter -list. +A user-defined function object is created by a function definition +(see section \ref{function}). It should be called with an argument +list containing the same number of items as the function's formal +parameter list. +\indexii{user-defined}{function} +\index{function object} Special read-only attributes: \verb\func_code\ is the code object representing the compiled function body, and \verb\func_globals\ is (a reference to) the dictionary that holds the function's global -variables -- it implements the global name space of the module in +variables --- it implements the global name space of the module in which the function was defined. +\ttindex{func_code} +\ttindex{func_globals} +\indexii{global}{name space} \item[User-defined methods] A user-defined method (a.k.a. {\tt object closure}) is a pair of a @@ -784,28 +816,35 @@ called with an argument list containing one item less than the number of items in the function's formal parameter list. When called, the class instance becomes the first argument, and the call arguments are shifted one to the right. +\indexii{object}{closure} +indexii{user-defined}{method} Special read-only attributes: \verb\im_self\ is the class instance object, \verb\im_func\ is the function object. +\ttindex{im_func} +\ttindex{im_self} \item[Built-in functions] A built-in function object is a wrapper around a C function. Examples of built-in functions are \verb\len\ and \verb\math.sin\. There are no special attributes. The number and type of the arguments are determined by the C function. +\index{C} \item[Built-in methods] This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is \verb\list.append\ if \verb\list\ is a list object. +\indexii{built-in}{method} \item[Classes] Class objects are described below. When a class object is called as a parameterless function, a new class instance (also described below) is created and returned. The class's initialization function is not -called -- this is the responsibility of the caller. It is illegal to +called --- this is the responsibility of the caller. It is illegal to call a class object with one or more arguments. +\index{class} \end{description} @@ -818,11 +857,16 @@ Module attribute references are translated to lookups in this dictionary. A module object does not contain the code object used to initialize the module (since it isn't needed once the initialization is done). +\stindex{import} +\index{module} Attribute assignment update the module's name space dictionary. Special read-only attributes: \verb\__dict__\ yields the module's name -space as a dictionary object; \verb\__name__\ yields the module's name. +space as a dictionary object; \verb\__name__\ yields the module's name +as a string object. +\ttindex{__dict__} +\ttindex{__name__} \item[Classes] Class objects are created by class definitions (see section @@ -832,9 +876,14 @@ lookups in this dictionary. When an attribute name is not found there, the attribute search continues in the base classes. The search is depth-first, left-to-right in the order of their occurrence in the base class list. +\index{class} +\index{container} +\index{dictionary} +\indexii{class}{attribute} -Attribute assignments update the class's dictionary, never the +Class attribute assignments update the class's dictionary, never the dictionary of a base class. +\indexiii{class}{attribute}{assignment} A class can be called as a parameterless function to yield a class instance (see above). @@ -843,6 +892,8 @@ Special read-only attributes: \verb\__dict__\ yields te dictionary containing the class's name space; \verb\__bases__\ yields a tuple (possibly empty or a singleton) containing the base classes, in the order of their occurrence in the base class list. +\ttindex{__dict__} +\ttindex{__bases__} \item[Class instances] A class instance is created by calling a class object as a @@ -852,11 +903,16 @@ there, and the instance's class has an attribute by that name, and that class attribute is a user-defined function (and in no other cases), the instance attribute reference yields a user-defined method object (see above) constructed from the instance and the function. +\indexii{class}{instance} +\indexii{class instance}{attribute} Attribute assignments update the instance's dictionary. +\indexiii{class instance}{attribute}{assignment} Special read-only attributes: \verb\__dict__\ yields the attribute dictionary; \verb\__class__\ yields the instance's class. +\ttindex{__dict__} +\ttindex{__class__} \item[Files] A file object represents an open file. (It is a wrapper around a C @@ -867,11 +923,21 @@ the \verb\makefile\ method of socket objects. \verb\sys.stdin\, the the interpreter's standard input, output and error streams. See the Python Library Reference for methods of file objects and other details. +\index{file} +\index{C} +\index{stdio} +\bifuncindex{open} +\bifuncindex{popen} +\bifuncindex{makefile} +\ttindex{stdin} +\ttindex{stdout} +\ttindex{stderr} \item[Internal types] A few types used internally by the interpreter are exposed to the user. Their definition may change with future versions of the interpreter, but they are mentioned here for completeness. +\index{internal type} \begin{description} @@ -881,6 +947,7 @@ object and a function object is that the function object contains an explicit reference to the function's context (the module in which it was defined) which a code object contains no context. There is no way to execute a bare code object. +\index{code object} Special read-only attributes: \verb\co_code\ is a string representing the sequence of instructions; \verb\co_consts\ is a list of literals @@ -889,10 +956,15 @@ the code; \verb\co_filename\ is the filename from which the code was compiled. (To find out the line numbers, you would have to decode the instructions; the standard library module \verb\dis\ contains an example of how to do this.) +\ttindex{co_code} +\ttindex{co_consts} +\ttindex{co_names} +\ttindex{co_filename} \item[Frame objects] Frame objects represent execution frames. They may occur in traceback objects (see below). +\index{frame object} Special read-only attributes: \verb\f_back\ is to the previous stack frame (towards the caller), or \verb\None\ if this is the bottom @@ -902,6 +974,12 @@ variables; \verb\f_locals\ is used for local variables; \verb\f_lineno\ gives the line number and \verb\f_lasti\ gives the precise instruction (this is an index into the instruction string of the code object). +\ttindex{f_back} +\ttindex{f_code} +\ttindex{f_globals} +\ttindex{f_locals} +\ttindex{f_lineno} +\ttindex{f_lasti} \item[Traceback objects] Traceback objects represent a stack trace of an exception. A @@ -912,8 +990,14 @@ traceback. When an exception handler is entered, the stack trace is made available to the program as \verb\sys.exc_traceback\. When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is -interactive, it is made available to the user as +interactive, it is also made available to the user as \verb\sys.last_traceback\. +\index{traceback object} +\indexii{stack}{trace} +\index{exception handler} +\index{execution stack} +\ttindex{exc_traceback} +\ttindex{last_traceback} Special read-only attributes: \verb\tb_next\ is the next level in the stack trace (towards the frame where the exception occurred), or @@ -924,15 +1008,164 @@ precise instruction. The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a \verb\try\ statement with no matching \verb\except\ clause or with a \verb\finally\ clause. +\ttindex{tb_next} +\ttindex{tb_frame} +\ttindex{tb_lineno} +\ttindex{tb_lasti} +\stindex{try} \end{description} % Internal types \end{description} % Types +\chapter{Execution model} + +\section{Code blocks, execution frames, and name spaces} + +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 block 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} + +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 functions +\verb\eval\ and \verb\exec\ are code blocks. And finally, the +expression read and evaluated by the built-in function \verb\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. +\index{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 \verb\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 \verb\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 \verb\global\ statement forces global +interpretation of selected names throughout the code block. The +following constructs bind names: formal parameters, \verb\import\ +statements, class and function definitions (these bind the class or +function name), and targets that are identifiers if occurring in an +assignment, \verb\for\ loop header, or \verb\except\ clause header. +(A target occurring in a \verb\del\ statement does not bind a 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 \verb\builtin\). When a name is not +found at all, the \verb\NameError\ exception is raised. + +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. + +\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 \verb\__main__\ & same as global & \\ +Interactive command & n.s. for \verb\__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. & \\ +String passed to \verb\exec\ or \verb\eval\ + & global n.s. of caller & local n.s. of caller & (1) \\ +File read by \verb\execfile\ + & global n.s. of caller & local n.s. of caller & (1) \\ +Expression read by \verb\input\ + & global n.s. of caller & local n.s. of caller & \\ +\hline +\end{tabular} +\end{center} + +Notes: + +\begin{description} + +\item[n.s.] means {\em name space} + +\item[(1)] The global and local name space for these functions can be +overridden with optional extra arguments. + +\end{description} + +\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 \verb\raise\ statement. +Exception handlers are specified with the \verb\try...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. Two different string +objects with the same value identify different exceptions. + +When an exception is raised, an object (maybe \verb\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. + +See also the description of the \verb\try\ and \verb\raise\ +statements. + \chapter{Expressions and conditions} -From now on, extended BNF notation will be used to describe syntax, -not lexical analysis. +In this and the following chapters, extended BNF notation will be used +to describe syntax, not lexical analysis. +\index{BNF} This chapter explains the meaning of the elements of expressions and conditions. Conditions are a superset of expressions, and a condition @@ -942,7 +1175,7 @@ instead of conditions is in expression statements and on the right-hand side of assignments; this catches some nasty bugs like accedentally writing \verb\x == 1\ instead of \verb\x = 1\. -The comma has several roles in Python's syntax. It is usually an +The comma plays several roles in Python's syntax. It is usually an operator with a lower precedence than all others, but occasionally serves other purposes as well; e.g., it separates function arguments, is used in list and dictionary constructors, and has special semantics @@ -1037,7 +1270,7 @@ tuples are immutable, the rules for literals apply here. (Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which -parentheses {\em are} required -- allowing unparenthesized ``nothing'' +parentheses {\em are} required --- allowing unparenthesized ``nothing'' in expressions would causes ambiguities and allow common typos to pass uncaught.) @@ -1632,7 +1865,7 @@ messages.) pass_stmt: "pass" \end{verbatim} -\verb\pass\ is a null operation -- when it is executed, nothing +\verb\pass\ is a null operation --- when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example: @@ -2035,12 +2268,12 @@ When a \verb\return\ or \verb\break\ statement is executed in the \verb\try\ suite of a \verb\try...finally\ statement, the \verb\finally\ clause is also executed `on the way out'. A \verb\continue\ statement is illegal in the \verb\try\ clause (the -reason is a problem with the current implementation -- this +reason is a problem with the current implementation --- this restriction may be lifted in the future). \section{Function definitions} \label{function} -XXX +A function definition defines a function: \begin{verbatim} funcdef: "def" identifier "(" [parameter_list] ")" ":" suite @@ -2048,18 +2281,35 @@ parameter_list: parameter ("," parameter)* parameter: identifier | "(" parameter_list ")" \end{verbatim} -XXX +A function definition is an executable statement. Its execution binds +the function name in the current local name space to a function object +(a wrapper around the executable code for the function). This +function object contains a reference to the current global name space +as the global name space to be used when the function is called. + +The function definition does not execute the function body; this gets +executed only when the function is called. Function call semantics +are described elsewhere (see XXX). \section{Class definitions} \label{class} -XXX +A class definition defines a class: \begin{verbatim} classdef: "class" identifier [inheritance] ":" suite inheritance: "(" condition_list ")" \end{verbatim} -XXX +A class definition is an executable statement. It first executes the +inheritance list, if present. The class's suite is executed in a new +execution frame, using a newly created local name space and the +original global name space. (Usually, the suite contains only +function definitions.) When the class's suite finishes execution, its +execution frame is discarded but its local name space is saved. A +class object (see XXX) is created using the inheritance list for the +base classes and the saved local name space for the attribute +dictionary. The class name is then bound to this class object in the +original local name space. \section{P.M.} @@ -2067,4 +2317,6 @@ XXX Syntax for scripts, modules XXX Syntax for interactive input, eval, exec, execfile, input XXX New definition of expressions (as conditions) +\input{ref.ind} % The index + \end{document} |