1 \chapter{Lexical analysis
\label{lexical
}}
3 A Python program is read by a
\emph{parser
}. Input to the parser is a
4 stream of
\emph{tokens
}, generated by the
\emph{lexical analyzer
}. This
5 chapter describes how the lexical analyzer breaks a file into tokens.
6 \index{lexical analysis
}
10 Python uses the
7-bit
\ASCII{} character set for program text and string
11 literals.
8-bit characters may be used in string literals and comments
12 but their interpretation is platform dependent; the proper way to
13 insert
8-bit characters in string literals is by using octal or
14 hexadecimal escape sequences.
16 The run-time character set depends on the I/O devices connected to the
17 program but is generally a superset of
\ASCII{}.
19 \strong{Future compatibility note:
} It may be tempting to assume that the
20 character set for
8-bit characters is ISO Latin-
1 (an
\ASCII{}
21 superset that covers most western languages that use the Latin
22 alphabet), but it is possible that in the future Unicode text editors
23 will become common. These generally use the UTF-
8 encoding, which is
24 also an
\ASCII{} superset, but with very different use for the
25 characters with ordinals
128-
255. While there is no consensus on this
26 subject yet, it is unwise to assume either Latin-
1 or UTF-
8, even
27 though the current implementation appears to favor Latin-
1. This
28 applies both to the source character set and the run-time character
31 \section{Line structure
\label{line-structure
}}
33 A Python program is divided into a number of
\emph{logical lines
}.
34 \index{line structure
}
36 \subsection{Logical lines
\label{logical
}}
39 a logical line is represented by the token NEWLINE. Statements cannot
40 cross logical line boundaries except where NEWLINE is allowed by the
41 syntax (e.g., between statements in compound statements).
42 A logical line is constructed from one or more
\emph{physical lines
}
43 by following the explicit or implicit
\emph{line joining
} rules.
49 \subsection{Physical lines
\label{physical
}}
51 A physical line ends in whatever the current platform's convention is
52 for terminating lines. On
\UNIX{}, this is the
\ASCII{} LF (linefeed)
53 character. On DOS/Windows, it is the
\ASCII{} sequence CR LF (return
54 followed by linefeed). On Macintosh, it is the
\ASCII{} CR (return)
57 \subsection{Comments
\label{comments
}}
59 A comment starts with a hash character (
\code{\#
}) that is not part of
60 a string literal, and ends at the end of the physical line. A comment
61 signifies the end of the logical line unless the implicit line joining
63 Comments are ignored by the syntax; they are not tokens.
65 \index{hash character
}
67 \subsection{Explicit line joining
\label{explicit-joining
}}
69 Two or more physical lines may be joined into logical lines using
70 backslash characters (
\code{\e}), as follows: when a physical line ends
71 in a backslash that is not part of a string literal or comment, it is
72 joined with the following forming a single logical line, deleting the
73 backslash and the following end-of-line character. For example:
76 \index{line continuation
}
77 \index{backslash character
}
80 if
1900 < year <
2100 and
1 <= month <=
12 \
81 and
1 <= day <=
31 and
0 <= hour <
24 \
82 and
0 <= minute <
60 and
0 <= second <
60: # Looks like a valid date
86 A line ending in a backslash cannot carry a comment. A backslash does
87 not continue a comment. A backslash does not continue a token except
88 for string literals (i.e., tokens other than string literals cannot be
89 split across physical lines using a backslash). A backslash is
90 illegal elsewhere on a line outside a string literal.
93 \subsection{Implicit line joining
\label{implicit-joining
}}
95 Expressions in parentheses, square brackets or curly braces can be
96 split over more than one physical line without using backslashes.
100 month_names =
['Januari', 'Februari', 'Maart', # These are the
101 'April', 'Mei', 'Juni', # Dutch names
102 'Juli', 'Augustus', 'September', # for the months
103 'Oktober', 'November', 'December'
] # of the year
106 Implicitly continued lines can carry comments. The indentation of the
107 continuation lines is not important. Blank continuation lines are
108 allowed. There is no NEWLINE token between implicit continuation
109 lines. Implicitly continued lines can also occur within triple-quoted
110 strings (see below); in that case they cannot carry comments.
113 \subsection{Blank lines
\index{blank line
}\label{blank-lines
}}
115 A logical line that contains only spaces, tabs, formfeeds and possibly
116 a comment, is ignored (i.e., no NEWLINE token is generated). During
117 interactive input of statements, handling of a blank line may differ
118 depending on the implementation of the read-eval-print loop. In the
119 standard implementation, an entirely blank logical line (i.e.\ one
120 containing not even whitespace or a comment) terminates a multi-line
124 \subsection{Indentation
\label{indentation
}}
126 Leading whitespace (spaces and tabs) at the beginning of a logical
127 line is used to compute the indentation level of the line, which in
128 turn is used to determine the grouping of statements.
131 \index{leading whitespace
}
135 \index{statement grouping
}
137 First, tabs are replaced (from left to right) by one to eight spaces
138 such that the total number of characters up to and including the
139 replacement is a multiple of
140 eight (this is intended to be the same rule as used by
\UNIX{}). The
141 total number of spaces preceding the first non-blank character then
142 determines the line's indentation. Indentation cannot be split over
143 multiple physical lines using backslashes; the whitespace up to the
144 first backslash determines the indentation.
146 \strong{Cross-platform compatibility note:
} because of the nature of
147 text editors on non-UNIX platforms, it is unwise to use a mixture of
148 spaces and tabs for the indentation in a single source file.
150 A formfeed character may be present at the start of the line; it will
151 be ignored for the indentation calculations above. Formfeed
152 characters occurring elsewhere in the leading whitespace have an
153 undefined effect (for instance, they may reset the space count to
156 The indentation levels of consecutive lines are used to generate
157 INDENT and DEDENT tokens, using a stack, as follows.
161 Before the first line of the file is read, a single zero is pushed on
162 the stack; this will never be popped off again. The numbers pushed on
163 the stack will always be strictly increasing from bottom to top. At
164 the beginning of each logical line, the line's indentation level is
165 compared to the top of the stack. If it is equal, nothing happens.
166 If it is larger, it is pushed on the stack, and one INDENT token is
167 generated. If it is smaller, it
\emph{must
} be one of the numbers
168 occurring on the stack; all numbers on the stack that are larger are
169 popped off, and for each number popped off a DEDENT token is
170 generated. At the end of the file, a DEDENT token is generated for
171 each number remaining on the stack that is larger than zero.
173 Here is an example of a correctly (though confusingly) indented piece
178 # Compute the list of all permutations of l
182 for i in range(len(l)):
186 r.append(l
[i:i+
1] + x)
190 The following example shows various indentation errors:
193 def perm(l): # error: first line indented
194 for i in range(len(l)): # error: not indented
196 p = perm(l
[:i
] + l
[i+
1:
]) # error: unexpected indent
198 r.append(l
[i:i+
1] + x)
199 return r # error: inconsistent dedent
202 (Actually, the first three errors are detected by the parser; only the
203 last error is found by the lexical analyzer --- the indentation of
204 \code{return r
} does not match a level popped off the stack.)
206 \subsection{Whitespace between tokens
\label{whitespace
}}
208 Except at the beginning of a logical line or in string literals, the
209 whitespace characters space, tab and formfeed can be used
210 interchangeably to separate tokens. Whitespace is needed between two
211 tokens only if their concatenation could otherwise be interpreted as a
212 different token (e.g., ab is one token, but a b is two tokens).
214 \section{Other tokens
\label{other-tokens
}}
216 Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
217 exist:
\emph{identifiers
},
\emph{keywords
},
\emph{literals
},
218 \emph{operators
}, and
\emph{delimiters
}.
219 Whitespace characters (other than line terminators, discussed earlier)
220 are not tokens, but serve to delimit tokens.
222 ambiguity exists, a token comprises the longest possible string that
223 forms a legal token, when read from left to right.
225 \section{Identifiers and keywords
\label{identifiers
}}
227 Identifiers (also referred to as
\emph{names
}) are described by the following
233 identifier: (letter|"_") (letter|digit|"_")*
234 letter: lowercase | uppercase
240 Identifiers are unlimited in length. Case is significant.
242 \subsection{Keywords
\label{keywords
}}
244 The following identifiers are used as reserved words, or
245 \emph{keywords
} of the language, and cannot be used as ordinary
246 identifiers. They must be spelled exactly as written here:
%
248 \index{reserved word
}
252 assert elif from lambda return
253 break else global not try
254 class except if or while
255 continue exec import pass
259 % When adding keywords, use reswords.py for reformatting
261 \subsection{Reserved classes of identifiers
\label{id-classes
}}
263 Certain classes of identifiers (besides keywords) have special
266 \begin{tableiii
}{l|l|l
}{code
}{Form
}{Meaning
}{Notes
}
267 \lineiii{_*
}{Not imported by
\samp{from
\var{module
} import *
}}{(
1)
}
268 \lineiii{__*__
}{System-defined name
}{}
269 \lineiii{__*
}{Class-private name mangling
}{}
272 (XXX need section references here.)
277 \item[(
1)
] The special identifier
\samp{_
} is used in the interactive
278 interpreter to store the result of the last evaluation; it is stored
279 in the
\module{__builtin__
} module. When not in interactive mode,
280 \samp{_
} has no special meaning and is not defined.
284 \section{Literals
\label{literals
}}
286 Literals are notations for constant values of some built-in types.
290 \subsection{String literals
\label{strings
}}
292 String literals are described by the following lexical definitions:
293 \index{string literal
}
296 stringliteral: shortstring | longstring
297 shortstring: "'" shortstringitem* "'" | '"' shortstringitem* '"'
298 longstring: "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
299 shortstringitem: shortstringchar | escapeseq
300 longstringitem: longstringchar | escapeseq
301 shortstringchar: <any ASCII character except "\" or newline or the quote>
302 longstringchar: <any ASCII character except "\">
303 escapeseq: "\" <any ASCII character>
305 \index{ASCII@
\ASCII{}}
307 \index{triple-quoted string
}
308 \index{Unicode Consortium
}
309 \index{string!Unicode
}
310 In plain English: String literals can be enclosed in matching single
311 quotes (
\code{'
}) or double quotes (
\code{"
}). They can also be
312 enclosed in matching groups of three single or double quotes (these
313 are generally referred to as
\emph{triple-quoted strings
}). The
314 backslash (
\code{\e}) character is used to escape characters that
315 otherwise have a special meaning, such as newline, backslash itself,
316 or the quote character. String literals may optionally be prefixed
317 with a letter `r' or `R'; such strings are called
318 \dfn{raw strings
}\index{raw string
} and use different rules for
319 backslash escape sequences. A prefix of 'u' or 'U' makes the string
320 a Unicode string. Unicode strings use the Unicode character set as
321 defined by the Unicode Consortium and ISO~
10646. Some additional
322 escape sequences, described below, are available in Unicode strings.
324 In triple-quoted strings,
325 unescaped newlines and quotes are allowed (and are retained), except
326 that three unescaped quotes in a row terminate the string. (A
327 ``quote'' is the character used to open the string, i.e. either
328 \code{'
} or
\code{"
}.)
330 Unless an `r' or `R' prefix is present, escape sequences in strings
331 are interpreted according to rules similar
332 to those used by Standard
\C{}. The recognized escape sequences are:
333 \index{physical line
}
334 \index{escape sequence
}
338 \begin{tableii
}{l|l
}{code
}{Escape Sequence
}{Meaning
}
339 \lineii{\e\var{newline
}} {Ignored
}
340 \lineii{\e\e} {Backslash (
\code{\e})
}
341 \lineii{\e'
} {Single quote (
\code{'
})
}
342 \lineii{\e"
} {Double quote (
\code{"
})
}
343 \lineii{\e a
} {\ASCII{} Bell (BEL)
}
344 \lineii{\e b
} {\ASCII{} Backspace (BS)
}
345 \lineii{\e f
} {\ASCII{} Formfeed (FF)
}
346 \lineii{\e n
} {\ASCII{} Linefeed (LF)
}
347 \lineii{\e N\
{\var{name
}\
}}
348 {Character named
\var{name
} in the Unicode database (Unicode only)
}
349 \lineii{\e r
} {\ASCII{} Carriage Return (CR)
}
350 \lineii{\e t
} {\ASCII{} Horizontal Tab (TAB)
}
351 \lineii{\e u
\var{xxxx
}}
352 {Character with
16-bit hex value
\var{xxxx
} (Unicode only)
}
353 \lineii{\e U
\var{xxxxxxxx
}}
354 {Character with
32-bit hex value
\var{xxxxxxxx
} (Unicode only)
}
355 \lineii{\e v
} {\ASCII{} Vertical Tab (VT)
}
356 \lineii{\e\var{ooo
}} {\ASCII{} character with octal value
\var{ooo
}}
357 \lineii{\e x
\var{hh
}} {\ASCII{} character with hex value
\var{hh
}}
359 \index{ASCII@
\ASCII{}}
361 As in Standard C, up to three octal digits are accepted. However,
362 exactly two hex digits are taken in hex escapes.
364 Unlike Standard
\index{unrecognized escape sequence
}C,
365 all unrecognized escape sequences are left in the string unchanged,
366 i.e.,
\emph{the backslash is left in the string
}. (This behavior is
367 useful when debugging: if an escape sequence is mistyped, the
368 resulting output is more easily recognized as broken.) It is also
369 important to note that the escape sequences marked as ``(Unicode
370 only)'' in the table above fall into the category of unrecognized
371 escapes for non-Unicode string literals.
373 When an `r' or `R' prefix is present, a character following a
374 backslash is included in the string without change, and
\emph{all
375 backslashes are left in the string
}. For example, the string literal
376 \code{r"
\e n"
} consists of two characters: a backslash and a lowercase
377 `n'. String quotes can be escaped with a backslash, but the backslash
378 remains in the string; for example,
\code{r"
\e""
} is a valid string
379 literal consisting of two characters: a backslash and a double quote;
380 \code{r"
\e"
} is not a value string literal (even a raw string cannot
381 end in an odd number of backslashes). Specifically,
\emph{a raw
382 string cannot end in a single backslash
} (since the backslash would
383 escape the following quote character). Note also that a single
384 backslash followed by a newline is interpreted as those two characters
385 as part of the string,
\emph{not
} as a line continuation.
387 \subsection{String literal concatenation
\label{string-catenation
}}
389 Multiple adjacent string literals (delimited by whitespace), possibly
390 using different quoting conventions, are allowed, and their meaning is
391 the same as their concatenation. Thus,
\code{"hello" 'world'
} is
392 equivalent to
\code{"helloworld"
}. This feature can be used to reduce
393 the number of backslashes needed, to split long strings conveniently
394 across long lines, or even to add comments to parts of strings, for
398 re.compile("
[A-Za-z_
]" # letter or underscore
399 "
[A-Za-z0-
9_
]*" # letter, digit or underscore
403 Note that this feature is defined at the syntactical level, but
404 implemented at compile time. The `+' operator must be used to
405 concatenate string expressions at run time. Also note that literal
406 concatenation can use different quoting styles for each component
407 (even mixing raw strings and triple quoted strings).
410 \subsection{Unicode literals
\label{unicode
}}
412 XXX explain more here...
415 \subsection{Numeric literals
\label{numbers
}}
417 There are four types of numeric literals: plain integers, long
418 integers, floating point numbers, and imaginary numbers. There are no
419 complex literals (complex numbers can be formed by adding a real
420 number and an imaginary number).
422 \index{numeric literal
}
423 \index{integer literal
}
424 \index{plain integer literal
}
425 \index{long integer literal
}
426 \index{floating point literal
}
427 \index{hexadecimal literal
}
428 \index{octal literal
}
429 \index{decimal literal
}
430 \index{imaginary literal
}
431 \index{complex literal
}
433 Note that numeric literals do not include a sign; a phrase like
434 \code{-
1} is actually an expression composed of the unary operator
435 `
\code{-
}' and the literal
\code{1}.
437 \subsection{Integer and long integer literals
\label{integers
}}
439 Integer and long integer literals are described by the following
443 longinteger: integer ("l"|"L")
444 integer: decimalinteger | octinteger | hexinteger
445 decimalinteger: nonzerodigit digit* | "
0"
446 octinteger: "
0" octdigit+
447 hexinteger: "
0" ("x"|"X") hexdigit+
448 nonzerodigit: "
1"..."
9"
450 hexdigit: digit|"a"..."f"|"A"..."F"
453 Although both lower case `l' and upper case `L' are allowed as suffix
454 for long integers, it is strongly recommended to always use `L', since
455 the letter `l' looks too much like the digit `
1'.
457 Plain integer decimal literals must be at most
2147483647 (i.e., the
458 largest positive integer, using
32-bit arithmetic). Plain octal and
459 hexadecimal literals may be as large as
4294967295, but values larger
460 than
2147483647 are converted to a negative value by subtracting
461 4294967296. There is no limit for long integer literals apart from
462 what can be stored in available memory.
464 Some examples of plain and long integer literals:
467 7 2147483647 0177 0x80000000
468 3L 79228162514264337593543950336L 0377L 0x100000000L
471 \subsection{Floating point literals
\label{floating
}}
473 Floating point literals are described by the following lexical
477 floatnumber: pointfloat | exponentfloat
478 pointfloat:
[intpart
] fraction | intpart "."
479 exponentfloat: (nonzerodigit digit* | pointfloat) exponent
480 intpart: nonzerodigit digit* | "
0"
482 exponent: ("e"|"E")
["+"|"-"
] digit+
485 Note that the integer part of a floating point number cannot look like
486 an octal integer, though the exponent may look like an octal literal
487 but will always be interpreted using radix
10. For example,
488 \samp{1e010
} is legal, while
\samp{07.1} is a syntax error.
489 The allowed range of floating point literals is
490 implementation-dependent.
491 Some examples of floating point literals:
494 3.14 10.
.001 1e100
3.14e-10
497 Note that numeric literals do not include a sign; a phrase like
498 \code{-
1} is actually an expression composed of the operator
499 \code{-
} and the literal
\code{1}.
501 \subsection{Imaginary literals
\label{imaginary
}}
503 Imaginary literals are described by the following lexical definitions:
506 imagnumber: (floatnumber | intpart) ("j"|"J")
509 An imaginary literal yields a complex number with a real part of
510 0.0. Complex numbers are represented as a pair of floating point
511 numbers and have the same restrictions on their range. To create a
512 complex number with a nonzero real part, add a floating point number
513 to it, e.g.,
\code{(
3+
4j)
}. Some examples of imaginary literals:
516 3.14j
10.j
10j
.001j
1e100j
3.14e-10j
520 \section{Operators
\label{operators
}}
522 The following tokens are operators:
531 The comparison operators
\code{<>
} and
\code{!=
} are alternate
532 spellings of the same operator.
\code{!=
} is the preferred spelling;
533 \code{<>
} is obsolescent.
535 \section{Delimiters
\label{delimiters
}}
537 The following tokens serve as delimiters in the grammar:
547 The period can also occur in floating-point and imaginary literals. A
548 sequence of three periods has a special meaning as an ellipsis in slices.
549 The second half of the list, the augmented assignment operators, serve
550 lexically as delimiters, but also perform an operation.
552 The following printing ASCII characters have special meaning as part
553 of other tokens or are otherwise significant to the lexical analyzer:
559 The following printing
\ASCII{} characters are not used in Python. Their
560 occurrence outside string literals and comments is an unconditional
562 \index{ASCII@
\ASCII{}}