blob: 9ccfee6ce185cae9d6f29ddd04f96b76d22645b8 [file] [log] [blame]
Guido van Rossum46f3e001992-08-14 09:11:01 +00001\chapter{Lexical analysis}
2
3A Python program is read by a {\em parser}. Input to the parser is a
4stream of {\em tokens}, generated by the {\em lexical analyzer}. This
5chapter describes how the lexical analyzer breaks a file into tokens.
6\index{lexical analysis}
7\index{parser}
8\index{token}
9
10\section{Line structure}
11
12A Python program is divided in a number of logical lines. The end of
13a logical line is represented by the token NEWLINE. Statements cannot
14cross logical line boundaries except where NEWLINE is allowed by the
15syntax (e.g. between statements in compound statements).
16\index{line structure}
17\index{logical line}
18\index{NEWLINE token}
19
20\subsection{Comments}
21
Guido van Rossum6938f061994-08-01 12:22:53 +000022A comment starts with a hash character (\verb@#@) that is not part of
Guido van Rossum46f3e001992-08-14 09:11:01 +000023a string literal, and ends at the end of the physical line. A comment
24always signifies the end of the logical line. Comments are ignored by
25the syntax.
26\index{comment}
27\index{logical line}
28\index{physical line}
29\index{hash character}
30
Guido van Rossum6938f061994-08-01 12:22:53 +000031\subsection{Explicit line joining}
Guido van Rossum46f3e001992-08-14 09:11:01 +000032
33Two or more physical lines may be joined into logical lines using
34backslash characters (\verb/\/), as follows: when a physical line ends
35in a backslash that is not part of a string literal or comment, it is
36joined with the following forming a single logical line, deleting the
37backslash and the following end-of-line character. For example:
38\index{physical line}
39\index{line joining}
Guido van Rossum6938f061994-08-01 12:22:53 +000040\index{line continuation}
Guido van Rossum46f3e001992-08-14 09:11:01 +000041\index{backslash character}
42%
43\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +000044if 1900 < year < 2100 and 1 <= month <= 12 \
45 and 1 <= day <= 31 and 0 <= hour < 24 \
46 and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
47 return 1
Guido van Rossum46f3e001992-08-14 09:11:01 +000048\end{verbatim}
49
Guido van Rossum6938f061994-08-01 12:22:53 +000050A line ending in a backslash cannot carry a comment; a backslash does
51not continue a comment (but it does continue a string literal, see
52below).
53
54\subsection{Implicit line joining}
55
56Expressions in parentheses, square brackets or curly braces can be
57split over more than one physical line without using backslashes.
58For example:
59
60\begin{verbatim}
61month_names = ['Januari', 'Februari', 'Maart', # These are the
62 'April', 'Mei', 'Juni', # Dutch names
63 'Juli', 'Augustus', 'September', # for the months
64 'Oktober', 'November', 'December'] # of the year
65\end{verbatim}
66
67Implicitly continued lines can carry comments. The indentation of the
68continuation lines is not important. Blank continuation lines are
69allowed.
70
Guido van Rossum46f3e001992-08-14 09:11:01 +000071\subsection{Blank lines}
72
73A logical line that contains only spaces, tabs, and possibly a
74comment, is ignored (i.e., no NEWLINE token is generated), except that
75during interactive input of statements, an entirely blank logical line
76terminates a multi-line statement.
77\index{blank line}
78
79\subsection{Indentation}
80
81Leading whitespace (spaces and tabs) at the beginning of a logical
82line is used to compute the indentation level of the line, which in
83turn is used to determine the grouping of statements.
84\index{indentation}
85\index{whitespace}
86\index{leading whitespace}
87\index{space}
88\index{tab}
89\index{grouping}
90\index{statement grouping}
91
92First, tabs are replaced (from left to right) by one to eight spaces
93such that the total number of characters up to there is a multiple of
94eight (this is intended to be the same rule as used by {\UNIX}). The
95total number of spaces preceding the first non-blank character then
96determines the line's indentation. Indentation cannot be split over
97multiple physical lines using backslashes.
98
99The indentation levels of consecutive lines are used to generate
100INDENT and DEDENT tokens, using a stack, as follows.
101\index{INDENT token}
102\index{DEDENT token}
103
104Before the first line of the file is read, a single zero is pushed on
105the stack; this will never be popped off again. The numbers pushed on
106the stack will always be strictly increasing from bottom to top. At
107the beginning of each logical line, the line's indentation level is
108compared to the top of the stack. If it is equal, nothing happens.
109If it is larger, it is pushed on the stack, and one INDENT token is
110generated. If it is smaller, it {\em must} be one of the numbers
111occurring on the stack; all numbers on the stack that are larger are
112popped off, and for each number popped off a DEDENT token is
113generated. At the end of the file, a DEDENT token is generated for
114each number remaining on the stack that is larger than zero.
115
116Here is an example of a correctly (though confusingly) indented piece
117of Python code:
118
119\begin{verbatim}
120def perm(l):
121 # Compute the list of all permutations of l
122
123 if len(l) <= 1:
124 return [l]
125 r = []
126 for i in range(len(l)):
127 s = l[:i] + l[i+1:]
128 p = perm(s)
129 for x in p:
130 r.append(l[i:i+1] + x)
131 return r
132\end{verbatim}
133
134The following example shows various indentation errors:
135
136\begin{verbatim}
137 def perm(l): # error: first line indented
138 for i in range(len(l)): # error: not indented
139 s = l[:i] + l[i+1:]
140 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
141 for x in p:
142 r.append(l[i:i+1] + x)
143 return r # error: inconsistent dedent
144\end{verbatim}
145
146(Actually, the first three errors are detected by the parser; only the
147last error is found by the lexical analyzer --- the indentation of
Guido van Rossum6938f061994-08-01 12:22:53 +0000148\verb@return r@ does not match a level popped off the stack.)
Guido van Rossum46f3e001992-08-14 09:11:01 +0000149
150\section{Other tokens}
151
152Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
153exist: identifiers, keywords, literals, operators, and delimiters.
154Spaces and tabs are not tokens, but serve to delimit tokens. Where
155ambiguity exists, a token comprises the longest possible string that
156forms a legal token, when read from left to right.
157
158\section{Identifiers}
159
160Identifiers (also referred to as names) are described by the following
161lexical definitions:
162\index{identifier}
163\index{name}
164
165\begin{verbatim}
166identifier: (letter|"_") (letter|digit|"_")*
167letter: lowercase | uppercase
168lowercase: "a"..."z"
169uppercase: "A"..."Z"
170digit: "0"..."9"
171\end{verbatim}
172
173Identifiers are unlimited in length. Case is significant.
174
175\subsection{Keywords}
176
177The following identifiers are used as reserved words, or {\em
178keywords} of the language, and cannot be used as ordinary
179identifiers. They must be spelled exactly as written here:
180\index{keyword}
181\index{reserved word}
182
183\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000184access del from lambda return
185and elif global not try
186break else if or while
187class except import pass
188continue finally in print
189def for is raise
Guido van Rossum46f3e001992-08-14 09:11:01 +0000190\end{verbatim}
191
Guido van Rossum6938f061994-08-01 12:22:53 +0000192% When adding keywords, pipe it through keywords.py for reformatting
Guido van Rossum46f3e001992-08-14 09:11:01 +0000193
194\section{Literals} \label{literals}
195
196Literals are notations for constant values of some built-in types.
197\index{literal}
198\index{constant}
199
200\subsection{String literals}
201
202String literals are described by the following lexical definitions:
203\index{string literal}
204
205\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000206stringliteral: shortstring | longstring
207shortstring: "'" shortstringitem* "'" | '"' shortstringitem* '"'
208longstring: "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
209shortstringitem: shortstringchar | escapeseq
Guido van Rossumab330d41995-07-07 23:04:17 +0000210longstringitem: longstringchar | escapeseq
Guido van Rossum6938f061994-08-01 12:22:53 +0000211shortstringchar: <any ASCII character except "\" or newline or the quote>
212longstringchar: <any ASCII character except "\">
213escapeseq: "\" <any ASCII character>
Guido van Rossum46f3e001992-08-14 09:11:01 +0000214\end{verbatim}
215\index{ASCII}
216
Guido van Rossum6938f061994-08-01 12:22:53 +0000217In ``long strings'' (strings surrounded by sets of three quotes),
218unescaped newlines and quotes are allowed (and are retained), except
219that three unescaped quotes in a row terminate the string. (A
220``quote'' is the character used to open the string, i.e. either
221\verb/'/ or \verb/"/.)
222
223Escape sequences in strings are interpreted according to rules similar
224to those used by Standard C. The recognized escape sequences are:
Guido van Rossum46f3e001992-08-14 09:11:01 +0000225\index{physical line}
226\index{escape sequence}
227\index{Standard C}
228\index{C}
229
230\begin{center}
231\begin{tabular}{|l|l|}
232\hline
Guido van Rossum6938f061994-08-01 12:22:53 +0000233\verb/\/{\em newline} & Ignored \\
Guido van Rossum46f3e001992-08-14 09:11:01 +0000234\verb/\\/ & Backslash (\verb/\/) \\
235\verb/\'/ & Single quote (\verb/'/) \\
Guido van Rossum6938f061994-08-01 12:22:53 +0000236\verb/\"/ & Double quote (\verb/"/) \\
Guido van Rossum47b4c0f1995-03-15 11:25:32 +0000237\verb/\a/ & \ASCII{} Bell (BEL) \\
238\verb/\b/ & \ASCII{} Backspace (BS) \\
239%\verb/\E/ & \ASCII{} Escape (ESC) \\
240\verb/\f/ & \ASCII{} Formfeed (FF) \\
241\verb/\n/ & \ASCII{} Linefeed (LF) \\
242\verb/\r/ & \ASCII{} Carriage Return (CR) \\
243\verb/\t/ & \ASCII{} Horizontal Tab (TAB) \\
244\verb/\v/ & \ASCII{} Vertical Tab (VT) \\
245\verb/\/{\em ooo} & \ASCII{} character with octal value {\em ooo} \\
246\verb/\x/{\em xx...} & \ASCII{} character with hex value {\em xx...} \\
Guido van Rossum46f3e001992-08-14 09:11:01 +0000247\hline
248\end{tabular}
249\end{center}
250\index{ASCII}
251
252In strict compatibility with Standard C, up to three octal digits are
253accepted, but an unlimited number of hex digits is taken to be part of
254the hex escape (and then the lower 8 bits of the resulting hex number
255are used in all current implementations...).
256
257All unrecognized escape sequences are left in the string unchanged,
258i.e., {\em the backslash is left in the string.} (This behavior is
259useful when debugging: if an escape sequence is mistyped, the
260resulting output is more easily recognized as broken. It also helps a
261great deal for string literals used as regular expressions or
262otherwise passed to other modules that do their own escape handling.)
263\index{unrecognized escape sequence}
264
265\subsection{Numeric literals}
266
267There are three types of numeric literals: plain integers, long
268integers, and floating point numbers.
269\index{number}
270\index{numeric literal}
271\index{integer literal}
272\index{plain integer literal}
273\index{long integer literal}
274\index{floating point literal}
275\index{hexadecimal literal}
276\index{octal literal}
277\index{decimal literal}
278
279Integer and long integer literals are described by the following
280lexical definitions:
281
282\begin{verbatim}
283longinteger: integer ("l"|"L")
284integer: decimalinteger | octinteger | hexinteger
285decimalinteger: nonzerodigit digit* | "0"
286octinteger: "0" octdigit+
287hexinteger: "0" ("x"|"X") hexdigit+
288
289nonzerodigit: "1"..."9"
290octdigit: "0"..."7"
291hexdigit: digit|"a"..."f"|"A"..."F"
292\end{verbatim}
293
294Although both lower case `l' and upper case `L' are allowed as suffix
295for long integers, it is strongly recommended to always use `L', since
296the letter `l' looks too much like the digit `1'.
297
Guido van Rossuma5475471995-03-16 14:44:07 +0000298Plain integer decimal literals must be at most 2147483647 (i.e., the
299largest positive integer, using 32-bit arithmetic). Plain octal and
300hexadecimal literals may be as large as 4294967295, but values larger
301than 2147483647 are converted to a negative value by subtracting
3024294967296. There is no limit for long integer literals apart from
303what can be stored in available memory.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000304
305Some examples of plain and long integer literals:
306
307\begin{verbatim}
3087 2147483647 0177 0x80000000
3093L 79228162514264337593543950336L 0377L 0x100000000L
310\end{verbatim}
311
312Floating point literals are described by the following lexical
313definitions:
314
315\begin{verbatim}
316floatnumber: pointfloat | exponentfloat
317pointfloat: [intpart] fraction | intpart "."
318exponentfloat: (intpart | pointfloat) exponent
319intpart: digit+
320fraction: "." digit+
321exponent: ("e"|"E") ["+"|"-"] digit+
322\end{verbatim}
323
324The allowed range of floating point literals is
325implementation-dependent.
326
327Some examples of floating point literals:
328
329\begin{verbatim}
3303.14 10. .001 1e100 3.14e-10
331\end{verbatim}
332
333Note that numeric literals do not include a sign; a phrase like
Guido van Rossum6938f061994-08-01 12:22:53 +0000334\verb@-1@ is actually an expression composed of the operator
335\verb@-@ and the literal \verb@1@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000336
337\section{Operators}
338
339The following tokens are operators:
340\index{operators}
341
342\begin{verbatim}
343+ - * / %
344<< >> & | ^ ~
345< == > <= <> != >=
346\end{verbatim}
347
Guido van Rossum6938f061994-08-01 12:22:53 +0000348The comparison operators \verb@<>@ and \verb@!=@ are alternate
Guido van Rossum46f3e001992-08-14 09:11:01 +0000349spellings of the same operator.
350
351\section{Delimiters}
352
353The following tokens serve as delimiters or otherwise have a special
354meaning:
355\index{delimiters}
356
357\begin{verbatim}
358( ) [ ] { }
Guido van Rossum16d6e711994-08-08 12:30:22 +0000359, : . " ` '
360= ;
Guido van Rossum46f3e001992-08-14 09:11:01 +0000361\end{verbatim}
362
Guido van Rossum47b4c0f1995-03-15 11:25:32 +0000363The following printing \ASCII{} characters are not used in Python. Their
Guido van Rossum46f3e001992-08-14 09:11:01 +0000364occurrence outside string literals and comments is an unconditional
365error:
366\index{ASCII}
367
368\begin{verbatim}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000369@ $ ?
Guido van Rossum46f3e001992-08-14 09:11:01 +0000370\end{verbatim}
371
372They may be used by future versions of the language though!