A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer. This chapter describes how the lexical analyzer breaks a file into tokens. Show
Python reads program text as Unicode code points; the encoding of a source file can be given by an encoding declaration and defaults to UTF-8, see
PEP 3120 for details. If the source file cannot be decoded, a 2.1. Line structure¶A Python program is divided into a number of logical lines. 2.1.1. 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). A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules. 2.1.2. Physical lines¶A physical line is a sequence of characters terminated by an end-of-line sequence. In source files and strings, any of the standard platform line termination sequences can be used - the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), or the old Macintosh form using the ASCII CR (return) character. All of these forms can be used equally, regardless of platform. The end of input also serves as an implicit terminator for the final physical line. When embedding Python, source code strings should be passed to Python APIs using the standard C conventions for newline characters (the 2.1.4. Encoding declarations¶If a comment in the first or second line of the Python script matches the regular expression # -*- coding: <encoding-name> -*-
which is recognized also by GNU Emacs, and # vim:fileencoding=<encoding-name>
which is recognized by Bram Moolenaar’s VIM. If no encoding declaration is found, the default encoding is UTF-8. In addition, if the first bytes of the file are the UTF-8 byte-order mark ( If an encoding is declared, the encoding name must be recognized by Python (see Standard Encodings). The encoding is used for all lexical analysis, including string literals, comments and identifiers. 2.1.5. Explicit line joining¶Two or more physical lines may be joined into logical lines using backslash characters ( if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1 A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal. 2.1.6. Implicit line joining¶Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For example: month_names = ['Januari', 'Februari', 'Maart', # These are the 'April', 'Mei', 'Juni', # Dutch names 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments. 2.1.7. Blank lines¶A logical line that contains only spaces, tabs, formfeeds and possibly a comment, is ignored (i.e., no NEWLINE token is generated). During interactive input of statements, handling of a blank line may differ depending on the implementation of the read-eval-print loop. In the standard interactive interpreter, an entirely blank logical line (i.e. one containing not even whitespace or a comment) terminates a multi-line statement. 2.1.8. Indentation¶Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements. Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement 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 whitespace up to the first backslash determines the indentation. Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in
spaces; a Cross-platform compatibility note: because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the indentation in a single source file. It should also be noted that different platforms may explicitly limit the maximum indentation level. A formfeed character may be present at the start of the line; it will be ignored for the indentation calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero). The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows. Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero. Here is an example of a correctly (though confusingly) indented piece 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)): s = l[:i] + l[i+1:] 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 i in range(len(l)): # error: not indented s = l[:i] + l[i+1:] p = perm(l[:i] + l[i+1:]) # error: unexpected indent for x in p: r.append(l[i:i+1] + x) return r # error: inconsistent dedent (Actually, the first three errors are detected by the parser; only the last error is found by the lexical analyzer — the indentation of 2.1.9. Whitespace between tokens¶Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., ab is one token, but a b is two tokens). 2.2. Other tokens¶Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: identifiers, keywords, literals, operators, and delimiters. Whitespace characters (other than line terminators, discussed earlier) 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. 2.3. Identifiers and keywords¶Identifiers (also referred to as names) are described by the following lexical definitions. The syntax of identifiers in Python is based on the Unicode standard annex UAX-31, with elaboration and changes as defined below; see also PEP 3131 for further details. Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters Python 3.0 introduces additional characters from outside the ASCII range (see
PEP 3131). For these characters, the classification uses the version of the Unicode Character Database as included in the Identifiers are unlimited in length. Case is significant. identifier ::= The Unicode category codes mentioned above stand for:
All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC. A non-normative HTML file listing all valid identifier characters for Unicode 14.0.0 can be found at https://www.unicode.org/Public/14.0.0/ucd/DerivedCoreProperties.txt 2.3.1. Keywords¶The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here: False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield 2.3.2. Soft Keywords¶New in version 3.10. Some identifiers are only reserved under specific contexts. These are known as soft keywords. The
identifiers As soft keywords, their use with pattern matching is possible while still preserving compatibility with existing code that uses 2.3.3. Reserved classes of identifiers¶Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters: _* Not imported by _ In a Separately, the interactive
interpreter makes the result of the last evaluation available in the variable Elsewhere, Note The name
It is also commonly used for unused variables. __*__ System-defined names, informally known as “dunder” names. These names are
defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*
Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section Identifiers (Names). 2.4. Literals¶Literals are notations for constant values of some built-in types. 2.4.1. String and Bytes literals¶String literals are described by the following lexical definitions: stringliteral ::= [ bytesliteral ::= One syntactic restriction not indicated by these productions is that whitespace is not allowed between the In plain English: Both types of literals can be enclosed in matching single quotes ( Bytes literals are always prefixed with Both string and bytes literals may optionally be prefixed with a letter New in version 3.3: The New in version 3.3: Support for the unicode legacy literal ( A string literal with In triple-quoted literals, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the literal. (A “quote” is the character used to open the literal, i.e. either Unless an
Escape sequences only recognized in string literals are:
Notes:
Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the result. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals. Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, 2.4.2. String literal concatenation¶Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, re.compile("[A-Za-z_]" # letter or underscore "[A-Za-z0-9_]*" # letter, digit or underscore ) Note that this feature is defined at the syntactical level, but implemented at compile time. The ‘+’ operator must be used to concatenate string expressions at run time. Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings), and formatted string literals may be concatenated with plain string literals. 2.4.3. Formatted string literals¶New in version 3.6. A formatted string literal or f-string is a string literal that is prefixed with Escape sequences are decoded like in ordinary string literals (except when a literal is also marked as a raw string). After decoding, the grammar for the contents of the string is: f_string ::= ( The parts of the string outside curly braces are treated literally, except that
any doubled curly braces Expressions in formatted string literals are treated like regular Python expressions surrounded by parentheses, with a few exceptions. An empty expression is not allowed, and both Changed in version 3.7: Prior to Python 3.7, an When the equal sign New in version 3.8: The equal sign If a
conversion is specified, the result of evaluating the expression is converted before formatting. Conversion The
result is then formatted using the Top-level format specifiers may include nested replacement fields. These nested fields may include
their own conversion fields and format specifiers, but may not include more deeply nested replacement fields. The format specifier mini-language is the same as that used by the Formatted string literals may be concatenated, but replacement fields cannot be split across literals. Some examples of formatted string literals: >>> name = "Fred" >>> f"He said his name is {name!r}." "He said his name is 'Fred'." >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r "He said his name is 'Fred'." >>> width = 10 >>> precision = 4 >>> value = decimal.Decimal("12.34567") >>> f"result: {value:{width}.{precision}}" # nested fields 'result: 12.35' >>> today = datetime(year=2017, month=1, day=27) >>> f"{today:%B %d, %Y}" # using date format specifier 'January 27, 2017' >>> f"{today=:%B %d, %Y}" # using date format specifier and debugging 'today=January 27, 2017' >>> number = 1024 >>> f"{number:#0x}" # using integer format specifier '0x400' >>> foo = "bar" >>> f"{ foo = }" # preserves whitespace " foo = 'bar'" >>> line = "The mill's closed" >>> f"{line = }" 'line = "The mill\'s closed"' >>> f"{line = :20}" "line = The mill's closed " >>> f"{line = !r:20}" 'line = "The mill\'s closed" ' A consequence of sharing the same syntax as regular string literals is that characters in the replacement fields must not conflict with the quoting used in the outer formatted string literal: f"abc {a["x"]} def" # error: outer string literal ended prematurely f"abc {a['x']} def" # workaround: use different quoting Backslashes are not allowed in format expressions and will raise an error: f"newline: {ord('\n')}" # raises SyntaxError To include a value in which a backslash escape is required, create a temporary variable. >>> newline = ord('\n') >>> f"newline: {newline}" 'newline: 10' Formatted string literals cannot be used as docstrings, even if they do not include expressions. >>> def foo(): ... f"Not a docstring" ... >>> foo.__doc__ is None True See also PEP 498 for the proposal that added formatted string literals, and
2.4.4. Numeric literals¶There are three types of numeric literals: integers, floating point numbers, and imaginary numbers. There are no complex literals (complex numbers can be formed by adding a real number and an imaginary number). Note that numeric literals do not include a sign; a phrase like 2.4.5. Integer literals¶Integer literals are described by the following lexical definitions: integer ::= There is no limit for the length of integer literals apart from what can be stored in available memory. Underscores are ignored for determining the numeric value of the literal. They can be used to group digits for enhanced readability. One underscore can
occur between digits, and after base specifiers like Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0. Some examples of integer literals: 7 2147483647 0o177 0b100110111 3 79228162514264337593543950336 0o377 0xdeadbeef 100_000_000_000 0b_1110_0101 Changed in version 3.6: Underscores are now allowed for grouping purposes in literals. 2.4.6. Floating point literals¶Floating point literals are described by the following lexical definitions: floatnumber ::= Note that the integer and exponent parts are always interpreted using radix 10. For example, Some examples of floating point literals: 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93 Changed in version 3.6: Underscores are now allowed for grouping purposes in literals. 2.4.7. Imaginary literals¶Imaginary literals are described by the following lexical definitions: imagnumber ::= ( An imaginary literal yields a complex number with a real part of 0.0. Complex numbers are represented as a pair of floating point numbers and have the same restrictions on their range. To create a complex number with a nonzero real part, add a floating
point number to it, e.g., 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j 2.5. Operators¶The following tokens are operators: + - * ** / // % @ << >> & | ^ ~ := < > <= >= == != 2.6. Delimiters¶The following tokens serve as delimiters in the grammar: ( ) [ ] { } , : . ; @ = -> += -= *= /= //= %= @= &= |= ^= >>= <<= **= The period can also occur in floating-point and imaginary literals. A sequence of three periods has a special meaning as an ellipsis literal. The second half of the list, the augmented assignment operators, serve lexically as delimiters, but also perform an operation. The following printing ASCII characters have special meaning as part of other tokens or are otherwise significant to the lexical analyzer: The following printing ASCII characters are not used in Python. Their occurrence outside string literals and comments is an unconditional error: Footnotes 1https://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt |