2. Лексический анализ¶
A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer (also known as the tokenizer). This chapter describes how the lexical analyzer breaks a file into tokens.
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 SyntaxError is
raised.
2.1. Структура строк¶
Программа на Python разделена на несколько логических строк.
2.1.1. Логические строки¶
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. Физические строки¶
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 \n character,
representing ASCII LF, is the line terminator).
2.1.4. Объявление кодировки¶
Если комментарий в первой или второй строке скрипта Python соответствует регулярному выражению coding[=:]\s*([-\w.]+), этот комментарий обрабатывается как объявление кодировки; первая группа этого выражения задаёт кодировку файла с исходным кодом. Объявление кодировки должно располагаться на отдельной строке. Если это вторая строка, первая строка также должна быть строкой только с комментарием. Рекомендуемые формы записи кодировки
# -*- coding: <encoding-name> -*-
которые распознаются также GNU Emacs, и
# vim:fileencoding=<encoding-name>
которые распознаются редактором VIM Брэма Муленаара.
Если объявление кодировки не найдено, используется кодировка по умолчанию UTF-8. Если явная или неявная кодировка файла — UTF-8, начальная метка порядка байтов UTF-8 (b'\xef\xbb\xbf') игнорируется, а не вызывает синтаксическую ошибку.
Если кодировка объявлена, её имя должно распознаваться Python (см. Standard Encodings). Кодировка используется для всего лексического анализа, включая строковые литералы, комментарии и идентификаторы.
2.1.5. Явное объединение строк¶
Две или более физических строк могут быть объединены в логическую строку с помощью символа обратного слэша (\), следующим образом: если физическая строка оканчивается обратным слэшем, который не является частью строкового литерала или комментария, она объединяется с последующей строкой, формируя единую логическую строку, при этом удаляются сам обратный слэш и следующий символ конца строки. Например:
if 1900 < year < 2100 and 1 <= month <= 12 \
and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60: # Похоже на корректную дату
return 1
Строка, заканчивающаяся обратным слэшем, не может содержать комментарий. Обратный слэш не продолжает комментарий. Обратный слэш не делит токен, кроме строковых литералов (т.е. токены, отличные от строковых литералов, нельзя разделять на физические строки с помощью обратного слэша). В остальных местах строки вне строковых литералов использование обратного слэша запрещено.
2.1.6. Неявное объединение строк¶
Выражения в круглых, квадратных или фигурных скобках можно разделить на несколько физических строк без использования обратного слэша. Например:
month_names = ['Januari', 'Februari', 'Maart', # Это
'April', 'Mei', 'Juni', # голландские названия
'Juli', 'Augustus', 'September', # месяцев
'Oktober', 'November', 'December'] # в году
Строки, продолжающиеся неявно, могут содержать комментарии. Отступ строк продолжения не важен. Допускаются также пустые строки продолжения. Между строками неявного продолжения нет токена NEWLINE. Неявно продолжающиеся строки также могут встречаться в строках, заключенных в тройные кавычки (см. ниже); в этом случае комментраии в них запрещены.
2.1.7. Пустые строки¶
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. Отступы¶
Ведущие пробельные символы (пробелы и табуляции) в начале логической строки определяют уровень её отступа, который, в свою очередь, используется для определения группировки инструкций.
Табуляции заменяются (слева направо) на несколько пробелов — от одного до восьми — так, чтобы общее количество символов от начала строки до конца замены включительно было кратно восьми (это соответствует правилу, используемому в Unix). Количество пробелов перед первым непустым символом определяет отступ строки. Отступы нельзя разделять на несколько физических строк с помощью обратного слэша; пробельные символы до первого обратного слэша определяют отступ.
Отступы отклоняются как непоследовательные, если в исходном файле табуляции и пробелы смешаны таким образом, что смысл кода зависит от того, сколько пробелов занимает одна табуляция. В этом случае возникает TabError.
Примечание о кроссплатформенной совместимости: из-за особенностей текстовых редакторов на платформах, отличных от UNIX, не рекомендуется использовать сочетание пробелов и табуляции для отступов в одном исходном файле. Также следует отметить, что разные платформы могут явно ограничивать максимальный уровень отступов.
Символ перевода страницы может присутствовать в начале строки; он игнорируется при вычислении уровня отступа. Символы перевода страницы, встречающиеся внутри начальных пробелов, имеют неопределённый эффект (например, они могут обнулить счётчик пробелов).
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.
Вот пример корректного (хотя и запутанного) фрагмента кода Python с отступами:
def perm(l):
# Вычисление списка всех перестановок 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
В следующем примере показаны различные ошибки отступов:
def perm(l): # ошибка: первая строка с отступом
for i in range(len(l)): # ошибка: нет отступа
s = l[:i] + l[i+1:]
p = perm(l[:i] + l[i+1:]) # ошибка: неожиданный отступ
for x in p:
r.append(l[i:i+1] + x)
return r # ошибка: несогласующееся уменьшение отступа
(На самом деле первые три ошибки обнаруживаются парсером; только последняя ошибка определяется лексическим анализатором — отступ return r не соответствует уровню, извлечённому из стека.)
2.1.9. Пробелы между токенами¶
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. Другие токены¶
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
include the uppercase and lowercase letters A through
Z, the underscore _ and, except for the first character, the digits
0 through 9.
Python 3.0 introduced 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 unicodedata module.
Identifiers are unlimited in length. Case is significant.
identifier ::=xid_startxid_continue* id_start ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property> id_continue ::= <all characters inid_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property> xid_start ::= <all characters inid_startwhose NFKC normalization is in "id_start xid_continue*"> xid_continue ::= <all characters inid_continuewhose NFKC normalization is in "id_continue*">
The Unicode category codes mentioned above stand for:
Lu - uppercase letters
Ll - lowercase letters
Lt - titlecase letters
Lm - modifier letters
Lo - other letters
Nl - letter numbers
Mn - nonspacing marks
Mc - spacing combining marks
Nd - decimal numbers
Pc - connector punctuations
Other_ID_Start - explicit list of characters in PropList.txt to support backwards compatibility
Other_ID_Continue - likewise
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 15.1.0 can be found at https://www.unicode.org/Public/15.1.0/ucd/DerivedCoreProperties.txt
2.3.1. Ключевые слова¶
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. Мягкие ключевые слова¶
Добавлено в версии 3.10.
Some identifiers are only reserved under specific contexts. These are known as
soft keywords. The identifiers match, case, type and _ can
syntactically act as keywords in certain contexts,
but this distinction is done at the parser level, not when tokenizing.
В качестве мягких ключевых слов их можно использовать в грамматике при сохранении совместимости с существующим кодом, где эти имена встречаются в качестве идентификаторов.
match, case, and _ are used in the match statement.
type is used in the type statement.
Изменено в версии 3.12: type теперь является мягким ключевым словом.
2.3.3. Зарезервированные классы идентификаторов¶
Некоторые классы идентификаторов (помимо ключевых слов) имеют особое значение. Эти классы определяются шаблонами начальных и конечных символов подчёркивания:
_*Не импортируются при использовании
from module import *._В шаблоне
caseвнутри инструкцииmatchсимвол_является мягким ключевым словом, обозначающим шаблон-подстановку.Отдельно стоит отметить, что в интерактивном интерпретаторе результат последнего вычисления доступен в переменной
_. (Она хранится в модулеbuiltinsнаряду со встроенными функциями, такими какprint.)В остальных случаях
_— обычный идентификатор. Его часто используют для именования «специальных» элементов, однако сам по себе он не имеет особого значения для Python.Примечание
Имя
_часто используется в сочетании с интернационализацией; обратитесь к документации модуляgettextдля получения дополнительной информации об этом соглашении.Оно также широко применяется для обозначения неиспользуемых переменных.
__*__Имена, определяемые системой, неформально называемые «dunder»-именами. Эти имена определяются интерпретатором и его реализацией (включая стандартную библиотеку). Текущие системные имена обсуждаются в разделе Special method names и в других местах документации. Вероятно, в будущих версиях Python будет добавлено ещё больше таких имён. Любое использование имён вида
__*__в любом контексте, не соответствующее явно задокументированному назначению, может привести к сбоям без предупреждения.__*Имена, приватные для класса. Имена этой категории при использовании внутри определения класса автоматически преобразуются в искажённую форму, что помогает избежать конфликтов имён между «приватными» атрибутами базовых и производных классов. См. раздел Identifiers (Names).
2.4. Литералы¶
Литералы — это явная запись постоянных значений некоторых встроенных типов.
2.4.1. Строковые и байтовые литералы¶
String literals are described by the following lexical definitions:
stringliteral ::= [stringprefix](shortstring|longstring) stringprefix ::= "r" | "u" | "R" | "U" | "f" | "F" | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF" shortstring ::= "'"shortstringitem* "'" | '"'shortstringitem* '"' longstring ::= "'''"longstringitem* "'''" | '"""'longstringitem* '"""' shortstringitem ::=shortstringchar|stringescapeseqlongstringitem ::=longstringchar|stringescapeseqshortstringchar ::= <any source character except "\" or newline or the quote> longstringchar ::= <any source character except "\"> stringescapeseq ::= "\" <any source character>
bytesliteral ::=bytesprefix(shortbytes|longbytes) bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB" shortbytes ::= "'"shortbytesitem* "'" | '"'shortbytesitem* '"' longbytes ::= "'''"longbytesitem* "'''" | '"""'longbytesitem* '"""' shortbytesitem ::=shortbyteschar|bytesescapeseqlongbytesitem ::=longbyteschar|bytesescapeseqshortbyteschar ::= <any ASCII character except "\" or newline or the quote> longbyteschar ::= <any ASCII character except "\"> bytesescapeseq ::= "\" <any ASCII character>
One syntactic restriction not indicated by these productions is that whitespace
is not allowed between the stringprefix or
bytesprefix and the rest of the literal. The source
character set is defined by the encoding declaration; it is UTF-8 if no encoding
declaration is given in the source file; see section Объявление кодировки.
In plain English: Both types of literals can be enclosed in matching single quotes
(') or double quotes ("). They can also be enclosed in matching groups
of three single or double quotes (these are generally referred to as
triple-quoted strings). The backslash (\) character is used to give special
meaning to otherwise ordinary characters like n, which means „newline“ when
escaped (\n). It can also be used to escape characters that otherwise have a
special meaning, such as newline, backslash itself, or the quote character.
See escape sequences below for examples.
Bytes literals are always prefixed with 'b' or 'B'; they produce an
instance of the bytes type instead of the str type. They
may only contain ASCII characters; bytes with a numeric value of 128 or greater
must be expressed with escapes.
Both string and bytes literals may optionally be prefixed with a letter 'r'
or 'R'; such constructs are called raw string literals
and raw bytes literals respectively and treat backslashes as
literal characters. As a result, in raw string literals, '\U' and '\u'
escapes are not treated specially.
Добавлено в версии 3.3: Префикс 'rb' для сырых байтовых литералов был добавлен как синоним 'br'.
Поддержка устаревшего литерала Unicode (u'value') была вновь введена для упрощения сопровождения кодовых баз, совместимых с Python 2.x и 3.x. Дополнительные сведения см. в PEP 414.
A string literal with 'f' or 'F' in its prefix is a
formatted string literal; see f-строки. The 'f' may be
combined with 'r', but not with 'b' or 'u', therefore raw
formatted strings are possible, but formatted bytes literals are not.
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 ' or ".)
2.4.1.1. Экранированные последовательности¶
Unless an 'r' or 'R' prefix is present, escape sequences in string and
bytes literals are interpreted according to rules similar to those used by
Standard C. The recognized escape sequences are:
Экранированная последовательность |
Значение |
Notes |
|---|---|---|
|
Backslash and newline ignored |
(1) |
|
Backslash ( |
|
|
Single quote ( |
|
|
Double quote ( |
|
|
Сигнал «звонка» ASCII (BEL) |
|
|
Возврат каретки назад ASCII (BS) |
|
|
Перевод страницы ASCII (FF) |
|
|
Перевод строки ASCII (LF) |
|
|
Возврат каретки ASCII (CR) |
|
|
Горизонтальная табуляция ASCII (TAB) |
|
|
Вертикальная табуляция ASCII (VT) |
|
|
Character with octal value ooo |
(2,4) |
|
Character with hex value hh |
(3,4) |
Escape sequences only recognized in string literals are:
Экранированная последовательность |
Значение |
Notes |
|---|---|---|
|
Character named name in the Unicode database |
(5) |
|
Character with 16-bit hex value xxxx |
(6) |
|
Character with 32-bit hex value xxxxxxxx |
(7) |
Notes:
В конце строки можно добавить обратный слэш, чтобы игнорировать перевод строки:
>>> 'Эта строка не будет включать \ ... обратные слэши или символы перевода строки.' 'Эта строка не будет включать обратные слэши или символы перевода строки.'
Того же результата можно добиться, используя строки в тройных кавычках или круглые скобки и конкатенацию строковых литералов.
As in Standard C, up to three octal digits are accepted.
Изменено в версии 3.11: Octal escapes with value larger than
0o377produce aDeprecationWarning.Изменено в версии 3.12: Octal escapes with value larger than
0o377produce aSyntaxWarning. In a future Python version they will be eventually aSyntaxError.В отличие от стандарта языка C требуется ровно две шестнадцатеричные цифры.
In a bytes literal, hexadecimal and octal escapes denote the byte with the given value. In a string literal, these escapes denote a Unicode character with the given value.
Изменено в версии 3.3: Support for name aliases [1] has been added.
Exactly four hex digits are required.
Any Unicode character can be encoded this way. Exactly eight hex digits are required.
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.
Изменено в версии 3.6: Нераспознанные экранированные последовательности вызывают DeprecationWarning.
Изменено в версии 3.12: Unrecognized escape sequences produce a SyntaxWarning. In a future
Python version they will be eventually a SyntaxError.
Даже в сыром литерале кавычки можно экранировать обратным слэшем, но сам слэш остаётся в результате; например, r"\"" — это корректный литерал, состоящий из двух символов: обратного слэша и двойной кавычки. Литерал r"\" не является допустимым (даже сырая строка не может заканчиваться нечётным числом слэшей). Конкретно, сырой литерал не может заканчиваться одним обратным слэшем (так как слэш экранировал бы следующую кавычку). Также обратный слэш, за которым идёт перевод строки, интерпретируется как два отдельных символа, а не как продолжение строки.
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, "hello" 'world' is equivalent to
"helloworld". This feature can be used to reduce the number of backslashes
needed, to split long strings conveniently across long lines, or even to add
comments to parts of strings, for example:
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. f-строки¶
Добавлено в версии 3.6.
A formatted string literal or f-string is a string literal
that is prefixed with 'f' or 'F'. These strings may contain
replacement fields, which are expressions delimited by curly braces {}.
While other string literals always have a constant value, formatted strings
are really expressions evaluated at run time.
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 ::= (literal_char| "{{" | "}}" |replacement_field)* replacement_field ::= "{"f_expression["="] ["!"conversion] [":"format_spec] "}" f_expression ::= (conditional_expression| "*"or_expr) (","conditional_expression| "," "*"or_expr)* [","] |yield_expressionconversion ::= "s" | "r" | "a" format_spec ::= (literal_char|replacement_field)* literal_char ::= <any code point except "{", "}" or NULL>
The parts of the string outside curly braces are treated literally,
except that any doubled curly braces '{{' or '}}' are replaced
with the corresponding single curly brace. A single opening curly
bracket '{' marks a replacement field, which starts with a
Python expression. To display both the expression text and its value after
evaluation, (useful in debugging), an equal sign '=' may be added after the
expression. A conversion field, introduced by an exclamation point '!' may
follow. A format specifier may also be appended, introduced by a colon ':'.
A replacement field ends with a closing curly bracket '}'.
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 lambda and
assignment expressions := must be surrounded by explicit parentheses.
Each expression is evaluated in the context where the formatted string literal
appears, in order from left to right. Replacement expressions can contain
newlines in both single-quoted and triple-quoted f-strings and they can contain
comments. Everything that comes after a # inside a replacement field
is a comment (even closing braces and quotes). In that case, replacement fields
must be closed in a different line.
>>> f"abc{a # This is a comment }"
... + 3}"
'abc5'
Изменено в версии 3.7: Prior to Python 3.7, an await expression and comprehensions
containing an async for clause were illegal in the expressions
in formatted string literals due to a problem with the implementation.
Изменено в версии 3.12: Prior to Python 3.12, comments were not allowed inside f-string replacement fields.
When the equal sign '=' is provided, the output will have the expression
text, the '=' and the evaluated value. Spaces after the opening brace
'{', within the expression and after the '=' are all retained in the
output. By default, the '=' causes the repr() of the expression to be
provided, unless there is a format specified. When a format is specified it
defaults to the str() of the expression unless a conversion '!r' is
declared.
Добавлено в версии 3.8: The equal sign '='.
If a conversion is specified, the result of evaluating the expression
is converted before formatting. Conversion '!s' calls str() on
the result, '!r' calls repr(), and '!a' calls ascii().
The result is then formatted using the format() protocol. The
format specifier is passed to the __format__() method of the
expression or conversion result. An empty string is passed when the
format specifier is omitted. The formatted result is then included in
the final value of the whole string.
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 str.format() method.
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" '
Допускается повторное использование того же типа кавычек, которые используются для внешней f-строки, внутри поля подстановки:
>>> a = dict(x=2)
>>> f"abc {a["x"]} def"
'abc 2 def'
Изменено в версии 3.12: Prior to Python 3.12, reuse of the same quoting type of the outer f-string inside a replacement field was not possible.
Обратные слэши также разрешены в полях подстановки и обрабатываются так же, как и в любом другом контексте:
>>> a = ["a", "b", "c"]
>>> print(f"Список a содержит:\n{"\n".join(a)}")
Список a содержит:
a
b
c
Изменено в версии 3.12: Prior to Python 3.12, backslashes were not permitted inside an f-string replacement field.
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 str.format(), which uses a related format string mechanism.
2.4.4. Числовые литералы¶
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 -1 is
actually an expression composed of the unary operator „-“ and the literal
1.
2.4.5. Целочисленные литералы¶
Integer literals are described by the following lexical definitions:
integer ::=decinteger|bininteger|octinteger|hexintegerdecinteger ::=nonzerodigit(["_"]digit)* | "0"+ (["_"] "0")* bininteger ::= "0" ("b" | "B") (["_"]bindigit)+ octinteger ::= "0" ("o" | "O") (["_"]octdigit)+ hexinteger ::= "0" ("x" | "X") (["_"]hexdigit)+ nonzerodigit ::= "1"..."9" digit ::= "0"..."9" bindigit ::= "0" | "1" octdigit ::= "0"..."7" hexdigit ::=digit| "a"..."f" | "A"..."F"
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 0x.
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
Изменено в версии 3.6: Подчёркивания теперь разрешены для визуального группирования цифр в литералах.
2.4.6. Литералы с плавающей точкой¶
Floating-point literals are described by the following lexical definitions:
floatnumber ::=pointfloat|exponentfloatpointfloat ::= [digitpart]fraction|digitpart"." exponentfloat ::= (digitpart|pointfloat)exponentdigitpart ::=digit(["_"]digit)* fraction ::= "."digitpartexponent ::= ("e" | "E") ["+" | "-"]digitpart
Note that the integer and exponent parts are always interpreted using radix 10.
For example, 077e010 is legal, and denotes the same number as 77e10. The
allowed range of floating-point literals is implementation-dependent. As in
integer literals, underscores are supported for digit grouping.
Some examples of floating-point literals:
3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93
Изменено в версии 3.6: Подчёркивания теперь разрешены для визуального группирования цифр в литералах.
2.4.7. Мнимые литералы¶
Imaginary literals are described by the following lexical definitions:
imagnumber ::= (floatnumber|digitpart) ("j" | "J")
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+4j). Some examples of
imaginary literals:
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
2.1.3. Комментарии¶
Комментарий начинается с символа решётки (
#), который не является частью строкового литерала, и заканчивается в конце физической строки. Комментарий обозначает конец логической строки, если не применяются правила неявного объединения строк. Комментарии игнорируются синтаксисом.