cpython / Doc / ref2.tex

Full commit
\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}

\section{Line structure}

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}


A comment starts with a hash character (\verb\#\) that is not part of
always signifies the end of the logical line.  Comments are ignored by
the syntax.
\index{logical line}
\index{physical line}
\index{hash character}

\subsection{Line joining}

Two or more physical lines may be joined into logical lines using
backslash characters (\verb/\/), as follows: when a physical line ends
joined with the following forming a single logical line, deleting the
\index{physical line}
\index{line joining}
\index{backslash character}
month_names = ['Januari', 'Februari', 'Maart',     \
               'April',   'Mei',      'Juni',      \
               'Juli',    'Augustus', 'September', \
               'Oktober', 'November', 'December']

\subsection{Blank lines}

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}


turn is used to determine the grouping of statements.
\index{leading whitespace}
\index{statement grouping}

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
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}

the beginning of each logical line, the line's indentation level is
generated.  If it is smaller, it {\em must} be one of the numbers
each number remaining on the stack that is larger than zero.

of Python code:

def perm(l):
        # Compute the list of all permutations of l

    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
             p = perm(s)
             for x in p:
              r.append(l[i:i+1] + x)
    return r

The following example shows various indentation errors:

    def perm(l):                        # error: first line indented
            for x in p:
                    r.append(l[i:i+1] + x)
                return r                # error: inconsistent dedent

\verb\return r\ does not match a level popped off the stack.)

\section{Other tokens}

Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
Spaces and tabs are not tokens, but serve to delimit tokens.  Where
ambiguity exists, a token comprises the longest possible string that
forms a legal token, when read from left to right.


lexical definitions:

identifier:     (letter|"_") (letter|digit|"_")*
letter:         lowercase | uppercase
lowercase:      "a"..."z"
uppercase:      "A"..."Z"
digit:          "0"..."9"

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{reserved word}

and        del        for        in         print
break      elif       from       is         raise
class      else       global     not        return
continue   except     if         or         try
def        finally    import     pass       while

%	# This Python program sorts and formats the above table
%	import string
%	l = []
%	try:
%		while 1:
%			l = l + string.split(raw_input())
%	except EOFError:
%		pass
%	l.sort()
%	for i in range((len(l)+4)/5):
%		for j in range(i, len(l), 5):
%			print string.ljust(l[j], 10),
%		print

\section{Literals} \label{literals}


\subsection{String literals}

String literals are described by the following lexical definitions:
\index{string literal}

stringliteral:  "'" stringitem* "'"
stringitem:     stringchar | escapeseq
stringchar:     <any ASCII character except newline or "\" or "'">
escapeseq:      "'" <any ASCII character except newline>

String literals cannot span physical line boundaries.  Escape
sequences in strings are actually interpreted according to rules
similar to those used by Standard C.  The recognized escape sequences
\index{physical line}
\index{escape sequence}
\index{Standard C}

\verb/\\/	& Backslash (\verb/\/) \\
\verb/\'/	& Single quote (\verb/'/) \\
\verb/\a/	& ASCII Bell (BEL) \\
\verb/\b/	& ASCII Backspace (BS) \\
%\verb/\E/	& ASCII Escape (ESC) \\
\verb/\f/	& ASCII Formfeed (FF) \\
\verb/\n/	& ASCII Linefeed (LF) \\
\verb/\r/	& ASCII Carriage Return (CR) \\
\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...} \\

In strict compatibility with Standard C, up to three octal digits are
accepted, but an unlimited number of hex digits is taken to be part of
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 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.)
\index{unrecognized escape sequence}

\subsection{Numeric literals}

There are three types of numeric literals: plain integers, long
integers, and floating point numbers.
\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:

longinteger:    integer ("l"|"L")
integer:        decimalinteger | octinteger | hexinteger
decimalinteger: nonzerodigit digit* | "0"
octinteger:     "0" octdigit+

nonzerodigit:   "1"..."9"
octdigit:       "0"..."7"

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).  Plain octal and
hexadecimal literals may be as large as $2^{32} - 1$, but values
larger than $2^{31} - 1$ are converted to a negative value by
subtracting $2^{32}$.  There is no limit for long integer literals.

Some examples of plain and long integer literals:

7     2147483647                        0177    0x80000000
3L    79228162514264337593543950336L    0377L   0x100000000L

Floating point literals are described by the following lexical

floatnumber:    pointfloat | exponentfloat
pointfloat:     [intpart] fraction | intpart "."
exponentfloat:  (intpart | pointfloat) exponent
intpart:        digit+
fraction:       "." digit+
exponent:       ("e"|"E") ["+"|"-"] digit+

The allowed range of floating point literals is

Some examples of floating point literals:

3.14    10.    .001    1e100    3.14e-10

\verb\-1\ is actually an expression composed of the operator
\verb\-\ and the literal \verb\1\.


The following tokens are operators:

+       -       *       /       %
<<      >>      &       |       ^       ~
<       ==      >       <=      <>      !=      >=

The comparison operators \verb\<>\ and \verb\!=\ are alternate
spellings of the same operator.


The following tokens serve as delimiters or otherwise have a special

(       )       [       ]       {       }
;       ,       :       .       `       =

The following printing ASCII characters are not used in Python.  Their
occurrence outside string literals and comments is an unconditional

@       $       "       ?

They may be used by future versions of the language though!