1 \chapter{Lexical analysis
}
3 A Python program is read by a
{\em parser
}. Input to the parser is a
4 stream of
{\em tokens
}, generated by the
{\em lexical analyzer
}. This
5 chapter describes how the lexical analyzer breaks a file into tokens.
6 \index{lexical analysis
}
10 \section{Line structure
}
12 A Python program is divided in a number of logical lines. The end of
13 a logical line is represented by the token NEWLINE. Statements cannot
14 cross logical line boundaries except where NEWLINE is allowed by the
15 syntax (e.g. between statements in compound statements).
16 \index{line structure
}
22 A comment starts with a hash character (
\verb@#@) that is not part of
23 a string literal, and ends at the end of the physical line. A comment
24 always signifies the end of the logical line. Comments are ignored by
29 \index{hash character
}
31 \subsection{Explicit line joining
}
33 Two or more physical lines may be joined into logical lines using
34 backslash characters (
\verb/\/), as follows: when a physical line ends
35 in a backslash that is not part of a string literal or comment, it is
36 joined with the following forming a single logical line, deleting the
37 backslash and the following end-of-line character. For example:
40 \index{line continuation
}
41 \index{backslash character
}
44 if
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
50 A line ending in a backslash cannot carry a comment; a backslash does
51 not continue a comment (but it does continue a string literal, see
54 \subsection{Implicit line joining
}
56 Expressions in parentheses, square brackets or curly braces can be
57 split over more than one physical line without using backslashes.
61 month_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
67 Implicitly continued lines can carry comments. The indentation of the
68 continuation lines is not important. Blank continuation lines are
71 \subsection{Blank lines
}
73 A logical line that contains only spaces, tabs, and possibly a
74 comment, is ignored (i.e., no NEWLINE token is generated), except that
75 during interactive input of statements, an entirely blank logical line
76 terminates a multi-line statement.
79 \subsection{Indentation
}
81 Leading whitespace (spaces and tabs) at the beginning of a logical
82 line is used to compute the indentation level of the line, which in
83 turn is used to determine the grouping of statements.
86 \index{leading whitespace
}
90 \index{statement grouping
}
92 First, tabs are replaced (from left to right) by one to eight spaces
93 such that the total number of characters up to there is a multiple of
94 eight (this is intended to be the same rule as used by
{\UNIX}). The
95 total number of spaces preceding the first non-blank character then
96 determines the line's indentation. Indentation cannot be split over
97 multiple physical lines using backslashes.
99 The indentation levels of consecutive lines are used to generate
100 INDENT and DEDENT tokens, using a stack, as follows.
104 Before the first line of the file is read, a single zero is pushed on
105 the stack; this will never be popped off again. The numbers pushed on
106 the stack will always be strictly increasing from bottom to top. At
107 the beginning of each logical line, the line's indentation level is
108 compared to the top of the stack. If it is equal, nothing happens.
109 If it is larger, it is pushed on the stack, and one INDENT token is
110 generated. If it is smaller, it
{\em must
} be one of the numbers
111 occurring on the stack; all numbers on the stack that are larger are
112 popped off, and for each number popped off a DEDENT token is
113 generated. At the end of the file, a DEDENT token is generated for
114 each number remaining on the stack that is larger than zero.
116 Here is an example of a correctly (though confusingly) indented piece
121 # Compute the list of all permutations of l
126 for i in range(len(l)):
130 r.append(l
[i:i+
1] + x)
134 The following example shows various indentation errors:
137 def perm(l): # error: first line indented
138 for i in range(len(l)): # error: not indented
140 p = perm(l
[:i
] + l
[i+
1:
]) # error: unexpected indent
142 r.append(l
[i:i+
1] + x)
143 return r # error: inconsistent dedent
146 (Actually, the first three errors are detected by the parser; only the
147 last error is found by the lexical analyzer --- the indentation of
148 \verb@return r@ does not match a level popped off the stack.)
150 \section{Other tokens
}
152 Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
153 exist: identifiers, keywords, literals, operators, and delimiters.
154 Spaces and tabs are not tokens, but serve to delimit tokens. Where
155 ambiguity exists, a token comprises the longest possible string that
156 forms a legal token, when read from left to right.
158 \section{Identifiers
}
160 Identifiers (also referred to as names) are described by the following
166 identifier: (letter|"_") (letter|digit|"_")*
167 letter: lowercase | uppercase
173 Identifiers are unlimited in length. Case is significant.
175 \subsection{Keywords
}
177 The following identifiers are used as reserved words, or
{\em
178 keywords
} of the language, and cannot be used as ordinary
179 identifiers. They must be spelled exactly as written here:
181 \index{reserved word
}
184 access del from lambda return
185 and elif global not try
186 break else if or while
187 class except import pass
188 continue finally in print
192 % When adding keywords, pipe it through keywords.py for reformatting
194 \section{Literals
} \label{literals
}
196 Literals are notations for constant values of some built-in types.
200 \subsection{String literals
}
202 String literals are described by the following lexical definitions:
203 \index{string literal
}
206 stringliteral: shortstring | longstring
207 shortstring: "'" shortstringitem* "'" | '"' shortstringitem* '"'
208 longstring: "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
209 shortstringitem: shortstringchar | escapeseq
210 longstringitem: longstringchar | escapeseq
211 shortstringchar: <any ASCII character except "\" or newline or the quote>
212 longstringchar: <any ASCII character except "\">
213 escapeseq: "\" <any ASCII character>
217 In ``long strings'' (strings surrounded by sets of three quotes),
218 unescaped newlines and quotes are allowed (and are retained), except
219 that 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/"/.)
223 Escape sequences in strings are interpreted according to rules similar
224 to those used by Standard C. The recognized escape sequences are:
225 \index{physical line
}
226 \index{escape sequence
}
231 \begin{tabular
}{|l|l|
}
233 \verb/\/
{\em newline
} & Ignored \\
234 \verb/\\/ & Backslash (
\verb/\/) \\
235 \verb/\'/ & Single quote (
\verb/'/) \\
236 \verb/\"/ & Double quote (
\verb/"/) \\
237 \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...
} \\
252 In strict compatibility with Standard C, up to three octal digits are
253 accepted, but an unlimited number of hex digits is taken to be part of
254 the hex escape (and then the lower
8 bits of the resulting hex number
255 are used in all current implementations...).
257 All unrecognized escape sequences are left in the string unchanged,
258 i.e.,
{\em the backslash is left in the string.
} (This behavior is
259 useful when debugging: if an escape sequence is mistyped, the
260 resulting output is more easily recognized as broken. It also helps a
261 great deal for string literals used as regular expressions or
262 otherwise passed to other modules that do their own escape handling.)
263 \index{unrecognized escape sequence
}
265 \subsection{Numeric literals
}
267 There are three types of numeric literals: plain integers, long
268 integers, and floating point numbers.
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
}
279 Integer and long integer literals are described by the following
283 longinteger: integer ("l"|"L")
284 integer: decimalinteger | octinteger | hexinteger
285 decimalinteger: nonzerodigit digit* | "
0"
286 octinteger: "
0" octdigit+
287 hexinteger: "
0" ("x"|"X") hexdigit+
289 nonzerodigit: "
1"..."
9"
291 hexdigit: digit|"a"..."f"|"A"..."F"
294 Although both lower case `l' and upper case `L' are allowed as suffix
295 for long integers, it is strongly recommended to always use `L', since
296 the letter `l' looks too much like the digit `
1'.
298 Plain integer decimal literals must be at most
2147483647 (i.e., the
299 largest positive integer, using
32-bit arithmetic). Plain octal and
300 hexadecimal literals may be as large as
4294967295, but values larger
301 than
2147483647 are converted to a negative value by subtracting
302 4294967296. There is no limit for long integer literals apart from
303 what can be stored in available memory.
305 Some examples of plain and long integer literals:
308 7 2147483647 0177 0x80000000
309 3L 79228162514264337593543950336L 0377L 0x100000000L
312 Floating point literals are described by the following lexical
316 floatnumber: pointfloat | exponentfloat
317 pointfloat:
[intpart
] fraction | intpart "."
318 exponentfloat: (intpart | pointfloat) exponent
321 exponent: ("e"|"E")
["+"|"-"
] digit+
324 The allowed range of floating point literals is
325 implementation-dependent.
327 Some examples of floating point literals:
330 3.14 10.
.001 1e100
3.14e-10
333 Note that numeric literals do not include a sign; a phrase like
334 \verb@-
1@ is actually an expression composed of the operator
335 \verb@-@ and the literal
\verb@
1@.
339 The following tokens are operators:
348 The comparison operators
\verb@<>@ and
\verb@!=@ are alternate
349 spellings of the same operator.
353 The following tokens serve as delimiters or otherwise have a special
363 The following printing
\ASCII{} characters are not used in Python. Their
364 occurrence outside string literals and comments is an unconditional
372 They may be used by future versions of the language though!