blob: 2757ab15928d6e065fcb22fcbbc2b3a3e5581a9e [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
210shortstringchar: <any ASCII character except "\" or newline or the quote>
211longstringchar: <any ASCII character except "\">
212escapeseq: "\" <any ASCII character>
Guido van Rossum46f3e001992-08-14 09:11:01 +0000213\end{verbatim}
214\index{ASCII}
215
Guido van Rossum6938f061994-08-01 12:22:53 +0000216In ``long strings'' (strings surrounded by sets of three quotes),
217unescaped newlines and quotes are allowed (and are retained), except
218that three unescaped quotes in a row terminate the string. (A
219``quote'' is the character used to open the string, i.e. either
220\verb/'/ or \verb/"/.)
221
222Escape sequences in strings are interpreted according to rules similar
223to those used by Standard C. The recognized escape sequences are:
Guido van Rossum46f3e001992-08-14 09:11:01 +0000224\index{physical line}
225\index{escape sequence}
226\index{Standard C}
227\index{C}
228
229\begin{center}
230\begin{tabular}{|l|l|}
231\hline
Guido van Rossum6938f061994-08-01 12:22:53 +0000232\verb/\/{\em newline} & Ignored \\
Guido van Rossum46f3e001992-08-14 09:11:01 +0000233\verb/\\/ & Backslash (\verb/\/) \\
234\verb/\'/ & Single quote (\verb/'/) \\
Guido van Rossum6938f061994-08-01 12:22:53 +0000235\verb/\"/ & Double quote (\verb/"/) \\
Guido van Rossum47b4c0f1995-03-15 11:25:32 +0000236\verb/\a/ & \ASCII{} Bell (BEL) \\
237\verb/\b/ & \ASCII{} Backspace (BS) \\
238%\verb/\E/ & \ASCII{} Escape (ESC) \\
239\verb/\f/ & \ASCII{} Formfeed (FF) \\
240\verb/\n/ & \ASCII{} Linefeed (LF) \\
241\verb/\r/ & \ASCII{} Carriage Return (CR) \\
242\verb/\t/ & \ASCII{} Horizontal Tab (TAB) \\
243\verb/\v/ & \ASCII{} Vertical Tab (VT) \\
244\verb/\/{\em ooo} & \ASCII{} character with octal value {\em ooo} \\
245\verb/\x/{\em xx...} & \ASCII{} character with hex value {\em xx...} \\
Guido van Rossum46f3e001992-08-14 09:11:01 +0000246\hline
247\end{tabular}
248\end{center}
249\index{ASCII}
250
251In strict compatibility with Standard C, up to three octal digits are
252accepted, but an unlimited number of hex digits is taken to be part of
253the hex escape (and then the lower 8 bits of the resulting hex number
254are used in all current implementations...).
255
256All unrecognized escape sequences are left in the string unchanged,
257i.e., {\em the backslash is left in the string.} (This behavior is
258useful when debugging: if an escape sequence is mistyped, the
259resulting output is more easily recognized as broken. It also helps a
260great deal for string literals used as regular expressions or
261otherwise passed to other modules that do their own escape handling.)
262\index{unrecognized escape sequence}
263
264\subsection{Numeric literals}
265
266There are three types of numeric literals: plain integers, long
267integers, and floating point numbers.
268\index{number}
269\index{numeric literal}
270\index{integer literal}
271\index{plain integer literal}
272\index{long integer literal}
273\index{floating point literal}
274\index{hexadecimal literal}
275\index{octal literal}
276\index{decimal literal}
277
278Integer and long integer literals are described by the following
279lexical definitions:
280
281\begin{verbatim}
282longinteger: integer ("l"|"L")
283integer: decimalinteger | octinteger | hexinteger
284decimalinteger: nonzerodigit digit* | "0"
285octinteger: "0" octdigit+
286hexinteger: "0" ("x"|"X") hexdigit+
287
288nonzerodigit: "1"..."9"
289octdigit: "0"..."7"
290hexdigit: digit|"a"..."f"|"A"..."F"
291\end{verbatim}
292
293Although both lower case `l' and upper case `L' are allowed as suffix
294for long integers, it is strongly recommended to always use `L', since
295the letter `l' looks too much like the digit `1'.
296
Guido van Rossuma5475471995-03-16 14:44:07 +0000297Plain integer decimal literals must be at most 2147483647 (i.e., the
298largest positive integer, using 32-bit arithmetic). Plain octal and
299hexadecimal literals may be as large as 4294967295, but values larger
300than 2147483647 are converted to a negative value by subtracting
3014294967296. There is no limit for long integer literals apart from
302what can be stored in available memory.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000303
304Some examples of plain and long integer literals:
305
306\begin{verbatim}
3077 2147483647 0177 0x80000000
3083L 79228162514264337593543950336L 0377L 0x100000000L
309\end{verbatim}
310
311Floating point literals are described by the following lexical
312definitions:
313
314\begin{verbatim}
315floatnumber: pointfloat | exponentfloat
316pointfloat: [intpart] fraction | intpart "."
317exponentfloat: (intpart | pointfloat) exponent
318intpart: digit+
319fraction: "." digit+
320exponent: ("e"|"E") ["+"|"-"] digit+
321\end{verbatim}
322
323The allowed range of floating point literals is
324implementation-dependent.
325
326Some examples of floating point literals:
327
328\begin{verbatim}
3293.14 10. .001 1e100 3.14e-10
330\end{verbatim}
331
332Note that numeric literals do not include a sign; a phrase like
Guido van Rossum6938f061994-08-01 12:22:53 +0000333\verb@-1@ is actually an expression composed of the operator
334\verb@-@ and the literal \verb@1@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000335
336\section{Operators}
337
338The following tokens are operators:
339\index{operators}
340
341\begin{verbatim}
342+ - * / %
343<< >> & | ^ ~
344< == > <= <> != >=
345\end{verbatim}
346
Guido van Rossum6938f061994-08-01 12:22:53 +0000347The comparison operators \verb@<>@ and \verb@!=@ are alternate
Guido van Rossum46f3e001992-08-14 09:11:01 +0000348spellings of the same operator.
349
350\section{Delimiters}
351
352The following tokens serve as delimiters or otherwise have a special
353meaning:
354\index{delimiters}
355
356\begin{verbatim}
357( ) [ ] { }
Guido van Rossum16d6e711994-08-08 12:30:22 +0000358, : . " ` '
359= ;
Guido van Rossum46f3e001992-08-14 09:11:01 +0000360\end{verbatim}
361
Guido van Rossum47b4c0f1995-03-15 11:25:32 +0000362The following printing \ASCII{} characters are not used in Python. Their
Guido van Rossum46f3e001992-08-14 09:11:01 +0000363occurrence outside string literals and comments is an unconditional
364error:
365\index{ASCII}
366
367\begin{verbatim}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000368@ $ ?
Guido van Rossum46f3e001992-08-14 09:11:01 +0000369\end{verbatim}
370
371They may be used by future versions of the language though!