Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | .. _lexical: |
| 3 | |
| 4 | **************** |
| 5 | Lexical analysis |
| 6 | **************** |
| 7 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 8 | .. index:: lexical analysis, parser, token |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 9 | |
| 10 | A Python program is read by a *parser*. Input to the parser is a stream of |
| 11 | *tokens*, generated by the *lexical analyzer*. This chapter describes how the |
| 12 | lexical analyzer breaks a file into tokens. |
| 13 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 14 | Python reads program text as Unicode code points; the encoding of a source file |
| 15 | can be given by an encoding declaration and defaults to UTF-8, see :pep:`3120` |
| 16 | for details. If the source file cannot be decoded, a :exc:`SyntaxError` is |
| 17 | raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 | |
| 19 | |
| 20 | .. _line-structure: |
| 21 | |
| 22 | Line structure |
| 23 | ============== |
| 24 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 25 | .. index:: line structure |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 26 | |
| 27 | A Python program is divided into a number of *logical lines*. |
| 28 | |
| 29 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 30 | .. _logical-lines: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 31 | |
| 32 | Logical lines |
| 33 | ------------- |
| 34 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 35 | .. index:: logical line, physical line, line joining, NEWLINE token |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 36 | |
| 37 | The end of a logical line is represented by the token NEWLINE. Statements |
| 38 | cannot cross logical line boundaries except where NEWLINE is allowed by the |
| 39 | syntax (e.g., between statements in compound statements). A logical line is |
| 40 | constructed from one or more *physical lines* by following the explicit or |
| 41 | implicit *line joining* rules. |
| 42 | |
| 43 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 44 | .. _physical-lines: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 45 | |
| 46 | Physical lines |
| 47 | -------------- |
| 48 | |
| 49 | A physical line is a sequence of characters terminated by an end-of-line |
| 50 | sequence. In source files, any of the standard platform line termination |
| 51 | sequences can be used - the Unix form using ASCII LF (linefeed), the Windows |
Georg Brandl | c575c90 | 2008-09-13 17:46:05 +0000 | [diff] [blame] | 52 | form using the ASCII sequence CR LF (return followed by linefeed), or the old |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 53 | Macintosh form using the ASCII CR (return) character. All of these forms can be |
| 54 | used equally, regardless of platform. |
| 55 | |
| 56 | When embedding Python, source code strings should be passed to Python APIs using |
| 57 | the standard C conventions for newline characters (the ``\n`` character, |
| 58 | representing ASCII LF, is the line terminator). |
| 59 | |
| 60 | |
| 61 | .. _comments: |
| 62 | |
| 63 | Comments |
| 64 | -------- |
| 65 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 66 | .. index:: comment, hash character |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 67 | |
| 68 | A comment starts with a hash character (``#``) that is not part of a string |
| 69 | literal, and ends at the end of the physical line. A comment signifies the end |
| 70 | of the logical line unless the implicit line joining rules are invoked. Comments |
| 71 | are ignored by the syntax; they are not tokens. |
| 72 | |
| 73 | |
| 74 | .. _encodings: |
| 75 | |
| 76 | Encoding declarations |
| 77 | --------------------- |
| 78 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 79 | .. index:: source character set, encodings |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 80 | |
| 81 | If a comment in the first or second line of the Python script matches the |
| 82 | regular expression ``coding[=:]\s*([-\w.]+)``, this comment is processed as an |
| 83 | encoding declaration; the first group of this expression names the encoding of |
| 84 | the source code file. The recommended forms of this expression are :: |
| 85 | |
| 86 | # -*- coding: <encoding-name> -*- |
| 87 | |
| 88 | which is recognized also by GNU Emacs, and :: |
| 89 | |
| 90 | # vim:fileencoding=<encoding-name> |
| 91 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 92 | which is recognized by Bram Moolenaar's VIM. |
| 93 | |
| 94 | If no encoding declaration is found, the default encoding is UTF-8. In |
| 95 | addition, if the first bytes of the file are the UTF-8 byte-order mark |
| 96 | (``b'\xef\xbb\xbf'``), the declared file encoding is UTF-8 (this is supported, |
| 97 | among others, by Microsoft's :program:`notepad`). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 98 | |
| 99 | If an encoding is declared, the encoding name must be recognized by Python. The |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 100 | encoding is used for all lexical analysis, including string literals, comments |
| 101 | and identifiers. The encoding declaration must appear on a line of its own. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 102 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 103 | .. XXX there should be a list of supported encodings. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 104 | |
| 105 | |
| 106 | .. _explicit-joining: |
| 107 | |
| 108 | Explicit line joining |
| 109 | --------------------- |
| 110 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 111 | .. index:: physical line, line joining, line continuation, backslash character |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 112 | |
| 113 | Two or more physical lines may be joined into logical lines using backslash |
| 114 | characters (``\``), as follows: when a physical line ends in a backslash that is |
| 115 | not part of a string literal or comment, it is joined with the following forming |
| 116 | a single logical line, deleting the backslash and the following end-of-line |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 117 | character. For example:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 118 | |
| 119 | if 1900 < year < 2100 and 1 <= month <= 12 \ |
| 120 | and 1 <= day <= 31 and 0 <= hour < 24 \ |
| 121 | and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date |
| 122 | return 1 |
| 123 | |
| 124 | A line ending in a backslash cannot carry a comment. A backslash does not |
| 125 | continue a comment. A backslash does not continue a token except for string |
| 126 | literals (i.e., tokens other than string literals cannot be split across |
| 127 | physical lines using a backslash). A backslash is illegal elsewhere on a line |
| 128 | outside a string literal. |
| 129 | |
| 130 | |
| 131 | .. _implicit-joining: |
| 132 | |
| 133 | Implicit line joining |
| 134 | --------------------- |
| 135 | |
| 136 | Expressions in parentheses, square brackets or curly braces can be split over |
| 137 | more than one physical line without using backslashes. For example:: |
| 138 | |
| 139 | month_names = ['Januari', 'Februari', 'Maart', # These are the |
| 140 | 'April', 'Mei', 'Juni', # Dutch names |
| 141 | 'Juli', 'Augustus', 'September', # for the months |
| 142 | 'Oktober', 'November', 'December'] # of the year |
| 143 | |
| 144 | Implicitly continued lines can carry comments. The indentation of the |
| 145 | continuation lines is not important. Blank continuation lines are allowed. |
| 146 | There is no NEWLINE token between implicit continuation lines. Implicitly |
| 147 | continued lines can also occur within triple-quoted strings (see below); in that |
| 148 | case they cannot carry comments. |
| 149 | |
| 150 | |
| 151 | .. _blank-lines: |
| 152 | |
| 153 | Blank lines |
| 154 | ----------- |
| 155 | |
| 156 | .. index:: single: blank line |
| 157 | |
| 158 | A logical line that contains only spaces, tabs, formfeeds and possibly a |
| 159 | comment, is ignored (i.e., no NEWLINE token is generated). During interactive |
| 160 | input of statements, handling of a blank line may differ depending on the |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 161 | implementation of the read-eval-print loop. In the standard interactive |
| 162 | interpreter, an entirely blank logical line (i.e. one containing not even |
| 163 | whitespace or a comment) terminates a multi-line statement. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 164 | |
| 165 | |
| 166 | .. _indentation: |
| 167 | |
| 168 | Indentation |
| 169 | ----------- |
| 170 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 171 | .. index:: indentation, leading whitespace, space, tab, grouping, statement grouping |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 172 | |
| 173 | Leading whitespace (spaces and tabs) at the beginning of a logical line is used |
| 174 | to compute the indentation level of the line, which in turn is used to determine |
| 175 | the grouping of statements. |
| 176 | |
Georg Brandl | 861ac1f | 2008-12-15 08:43:10 +0000 | [diff] [blame] | 177 | Tabs are replaced (from left to right) by one to eight spaces such that the |
| 178 | total number of characters up to and including the replacement is a multiple of |
| 179 | eight (this is intended to be the same rule as used by Unix). The total number |
| 180 | of spaces preceding the first non-blank character then determines the line's |
| 181 | indentation. Indentation cannot be split over multiple physical lines using |
| 182 | backslashes; the whitespace up to the first backslash determines the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 183 | indentation. |
| 184 | |
Georg Brandl | 861ac1f | 2008-12-15 08:43:10 +0000 | [diff] [blame] | 185 | Indentation is rejected as inconsistent if a source file mixes tabs and spaces |
| 186 | in a way that makes the meaning dependent on the worth of a tab in spaces; a |
| 187 | :exc:`TabError` is raised in that case. |
| 188 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 189 | **Cross-platform compatibility note:** because of the nature of text editors on |
| 190 | non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the |
| 191 | indentation in a single source file. It should also be noted that different |
| 192 | platforms may explicitly limit the maximum indentation level. |
| 193 | |
| 194 | A formfeed character may be present at the start of the line; it will be ignored |
| 195 | for the indentation calculations above. Formfeed characters occurring elsewhere |
| 196 | in the leading whitespace have an undefined effect (for instance, they may reset |
| 197 | the space count to zero). |
| 198 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 199 | .. index:: INDENT token, DEDENT token |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 200 | |
| 201 | The indentation levels of consecutive lines are used to generate INDENT and |
| 202 | DEDENT tokens, using a stack, as follows. |
| 203 | |
| 204 | Before the first line of the file is read, a single zero is pushed on the stack; |
| 205 | this will never be popped off again. The numbers pushed on the stack will |
| 206 | always be strictly increasing from bottom to top. At the beginning of each |
| 207 | logical line, the line's indentation level is compared to the top of the stack. |
| 208 | If it is equal, nothing happens. If it is larger, it is pushed on the stack, and |
| 209 | one INDENT token is generated. If it is smaller, it *must* be one of the |
| 210 | numbers occurring on the stack; all numbers on the stack that are larger are |
| 211 | popped off, and for each number popped off a DEDENT token is generated. At the |
| 212 | end of the file, a DEDENT token is generated for each number remaining on the |
| 213 | stack that is larger than zero. |
| 214 | |
| 215 | Here is an example of a correctly (though confusingly) indented piece of Python |
| 216 | code:: |
| 217 | |
| 218 | def perm(l): |
| 219 | # Compute the list of all permutations of l |
| 220 | if len(l) <= 1: |
| 221 | return [l] |
| 222 | r = [] |
| 223 | for i in range(len(l)): |
| 224 | s = l[:i] + l[i+1:] |
| 225 | p = perm(s) |
| 226 | for x in p: |
| 227 | r.append(l[i:i+1] + x) |
| 228 | return r |
| 229 | |
| 230 | The following example shows various indentation errors:: |
| 231 | |
| 232 | def perm(l): # error: first line indented |
| 233 | for i in range(len(l)): # error: not indented |
| 234 | s = l[:i] + l[i+1:] |
| 235 | p = perm(l[:i] + l[i+1:]) # error: unexpected indent |
| 236 | for x in p: |
| 237 | r.append(l[i:i+1] + x) |
| 238 | return r # error: inconsistent dedent |
| 239 | |
| 240 | (Actually, the first three errors are detected by the parser; only the last |
| 241 | error is found by the lexical analyzer --- the indentation of ``return r`` does |
| 242 | not match a level popped off the stack.) |
| 243 | |
| 244 | |
| 245 | .. _whitespace: |
| 246 | |
| 247 | Whitespace between tokens |
| 248 | ------------------------- |
| 249 | |
| 250 | Except at the beginning of a logical line or in string literals, the whitespace |
| 251 | characters space, tab and formfeed can be used interchangeably to separate |
| 252 | tokens. Whitespace is needed between two tokens only if their concatenation |
| 253 | could otherwise be interpreted as a different token (e.g., ab is one token, but |
| 254 | a b is two tokens). |
| 255 | |
| 256 | |
| 257 | .. _other-tokens: |
| 258 | |
| 259 | Other tokens |
| 260 | ============ |
| 261 | |
| 262 | Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: |
| 263 | *identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace |
| 264 | characters (other than line terminators, discussed earlier) are not tokens, but |
| 265 | serve to delimit tokens. Where ambiguity exists, a token comprises the longest |
| 266 | possible string that forms a legal token, when read from left to right. |
| 267 | |
| 268 | |
| 269 | .. _identifiers: |
| 270 | |
| 271 | Identifiers and keywords |
| 272 | ======================== |
| 273 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 274 | .. index:: identifier, name |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 275 | |
| 276 | Identifiers (also referred to as *names*) are described by the following lexical |
Georg Brandl | e06de8b | 2008-05-05 21:42:51 +0000 | [diff] [blame] | 277 | definitions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 278 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 279 | The syntax of identifiers in Python is based on the Unicode standard annex |
Georg Brandl | e06de8b | 2008-05-05 21:42:51 +0000 | [diff] [blame] | 280 | UAX-31, with elaboration and changes as defined below; see also :pep:`3131` for |
| 281 | further details. |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 282 | |
| 283 | Within the ASCII range (U+0001..U+007F), the valid characters for identifiers |
Georg Brandl | e06de8b | 2008-05-05 21:42:51 +0000 | [diff] [blame] | 284 | are the same as in Python 2.x: the uppercase and lowercase letters ``A`` through |
| 285 | ``Z``, the underscore ``_`` and, except for the first character, the digits |
| 286 | ``0`` through ``9``. |
| 287 | |
| 288 | Python 3.0 introduces additional characters from outside the ASCII range (see |
| 289 | :pep:`3131`). For these characters, the classification uses the version of the |
| 290 | Unicode Character Database as included in the :mod:`unicodedata` module. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 291 | |
| 292 | Identifiers are unlimited in length. Case is significant. |
| 293 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 294 | .. productionlist:: |
| 295 | identifier: `id_start` `id_continue`* |
Mark Summerfield | 051d1dd | 2007-11-20 13:22:19 +0000 | [diff] [blame] | 296 | id_start: <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property> |
| 297 | id_continue: <all characters in `id_start`, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property> |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 298 | |
| 299 | The Unicode category codes mentioned above stand for: |
| 300 | |
| 301 | * *Lu* - uppercase letters |
| 302 | * *Ll* - lowercase letters |
| 303 | * *Lt* - titlecase letters |
| 304 | * *Lm* - modifier letters |
| 305 | * *Lo* - other letters |
| 306 | * *Nl* - letter numbers |
| 307 | * *Mn* - nonspacing marks |
| 308 | * *Mc* - spacing combining marks |
| 309 | * *Nd* - decimal numbers |
| 310 | * *Pc* - connector punctuations |
| 311 | |
| 312 | All identifiers are converted into the normal form NFC while parsing; comparison |
| 313 | of identifiers is based on NFC. |
| 314 | |
| 315 | A non-normative HTML file listing all valid identifier characters for Unicode |
| 316 | 4.1 can be found at |
| 317 | http://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 318 | |
Mark Summerfield | 051d1dd | 2007-11-20 13:22:19 +0000 | [diff] [blame] | 319 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 320 | .. _keywords: |
| 321 | |
| 322 | Keywords |
| 323 | -------- |
| 324 | |
| 325 | .. index:: |
| 326 | single: keyword |
| 327 | single: reserved word |
| 328 | |
| 329 | The following identifiers are used as reserved words, or *keywords* of the |
| 330 | language, and cannot be used as ordinary identifiers. They must be spelled |
| 331 | exactly as written here:: |
| 332 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 333 | False class finally is return |
| 334 | None continue for lambda try |
| 335 | True def from nonlocal while |
| 336 | and del global not with |
| 337 | as elif if or yield |
| 338 | assert else import pass |
| 339 | break except in raise |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 340 | |
| 341 | .. _id-classes: |
| 342 | |
| 343 | Reserved classes of identifiers |
| 344 | ------------------------------- |
| 345 | |
| 346 | Certain classes of identifiers (besides keywords) have special meanings. These |
| 347 | classes are identified by the patterns of leading and trailing underscore |
| 348 | characters: |
| 349 | |
| 350 | ``_*`` |
| 351 | Not imported by ``from module import *``. The special identifier ``_`` is used |
| 352 | in the interactive interpreter to store the result of the last evaluation; it is |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 353 | stored in the :mod:`builtins` module. When not in interactive mode, ``_`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 354 | has no special meaning and is not defined. See section :ref:`import`. |
| 355 | |
| 356 | .. note:: |
| 357 | |
| 358 | The name ``_`` is often used in conjunction with internationalization; |
| 359 | refer to the documentation for the :mod:`gettext` module for more |
| 360 | information on this convention. |
| 361 | |
| 362 | ``__*__`` |
| 363 | System-defined names. These names are defined by the interpreter and its |
| 364 | implementation (including the standard library); applications should not expect |
| 365 | to define additional names using this convention. The set of names of this |
| 366 | class defined by Python may be extended in future versions. See section |
| 367 | :ref:`specialnames`. |
| 368 | |
| 369 | ``__*`` |
| 370 | Class-private names. Names in this category, when used within the context of a |
| 371 | class definition, are re-written to use a mangled form to help avoid name |
| 372 | clashes between "private" attributes of base and derived classes. See section |
| 373 | :ref:`atom-identifiers`. |
| 374 | |
| 375 | |
| 376 | .. _literals: |
| 377 | |
| 378 | Literals |
| 379 | ======== |
| 380 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 381 | .. index:: literal, constant |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 382 | |
| 383 | Literals are notations for constant values of some built-in types. |
| 384 | |
| 385 | |
| 386 | .. _strings: |
| 387 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 388 | String and Bytes literals |
| 389 | ------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 390 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 391 | .. index:: string literal, bytes literal, ASCII |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 392 | |
| 393 | String literals are described by the following lexical definitions: |
| 394 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 395 | .. productionlist:: |
| 396 | stringliteral: [`stringprefix`](`shortstring` | `longstring`) |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 397 | stringprefix: "r" | "R" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 398 | shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"' |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 399 | longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""' |
| 400 | shortstringitem: `shortstringchar` | `stringescapeseq` |
| 401 | longstringitem: `longstringchar` | `stringescapeseq` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 402 | shortstringchar: <any source character except "\" or newline or the quote> |
| 403 | longstringchar: <any source character except "\"> |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 404 | stringescapeseq: "\" <any source character> |
| 405 | |
| 406 | .. productionlist:: |
| 407 | bytesliteral: `bytesprefix`(`shortbytes` | `longbytes`) |
| 408 | bytesprefix: "b" | "B" |
| 409 | shortbytes: "'" `shortbytesitem`* "'" | '"' `shortbytesitem`* '"' |
| 410 | longbytes: "'''" `longbytesitem`* "'''" | '"""' `longbytesitem`* '"""' |
| 411 | shortbytesitem: `shortbyteschar` | `bytesescapeseq` |
| 412 | longbytesitem: `longbyteschar` | `bytesescapeseq` |
| 413 | shortbyteschar: <any ASCII character except "\" or newline or the quote> |
| 414 | longbyteschar: <any ASCII character except "\"> |
| 415 | bytesescapeseq: "\" <any ASCII character> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 416 | |
| 417 | One syntactic restriction not indicated by these productions is that whitespace |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 418 | is not allowed between the :token:`stringprefix` or :token:`bytesprefix` and the |
| 419 | rest of the literal. The source character set is defined by the encoding |
| 420 | declaration; it is UTF-8 if no encoding declaration is given in the source file; |
| 421 | see section :ref:`encodings`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 422 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 423 | .. index:: triple-quoted string, Unicode Consortium, raw string |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 424 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 425 | In plain English: Both types of literals can be enclosed in matching single quotes |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 426 | (``'``) or double quotes (``"``). They can also be enclosed in matching groups |
| 427 | of three single or double quotes (these are generally referred to as |
| 428 | *triple-quoted strings*). The backslash (``\``) character is used to escape |
| 429 | characters that otherwise have a special meaning, such as newline, backslash |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 430 | itself, or the quote character. |
| 431 | |
| 432 | String literals may optionally be prefixed with a letter ``'r'`` or ``'R'``; |
Benjamin Peterson | a2f837f | 2008-04-28 21:05:10 +0000 | [diff] [blame] | 433 | such strings are called :dfn:`raw strings` and treat backslashes as literal |
| 434 | characters. As a result, ``'\U'`` and ``'\u'`` escapes in raw strings are not |
| 435 | treated specially. |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 436 | |
| 437 | Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an |
| 438 | instance of the :class:`bytes` type instead of the :class:`str` type. They |
| 439 | may only contain ASCII characters; bytes with a numeric value of 128 or greater |
| 440 | must be expressed with escapes. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 441 | |
| 442 | In triple-quoted strings, unescaped newlines and quotes are allowed (and are |
| 443 | retained), except that three unescaped quotes in a row terminate the string. (A |
| 444 | "quote" is the character used to open the string, i.e. either ``'`` or ``"``.) |
| 445 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 446 | .. index:: physical line, escape sequence, Standard C, C |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 447 | |
| 448 | Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in strings are |
| 449 | interpreted according to rules similar to those used by Standard C. The |
| 450 | recognized escape sequences are: |
| 451 | |
| 452 | +-----------------+---------------------------------+-------+ |
| 453 | | Escape Sequence | Meaning | Notes | |
| 454 | +=================+=================================+=======+ |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 455 | | ``\newline`` | Backslash and newline ignored | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 456 | +-----------------+---------------------------------+-------+ |
| 457 | | ``\\`` | Backslash (``\``) | | |
| 458 | +-----------------+---------------------------------+-------+ |
| 459 | | ``\'`` | Single quote (``'``) | | |
| 460 | +-----------------+---------------------------------+-------+ |
| 461 | | ``\"`` | Double quote (``"``) | | |
| 462 | +-----------------+---------------------------------+-------+ |
| 463 | | ``\a`` | ASCII Bell (BEL) | | |
| 464 | +-----------------+---------------------------------+-------+ |
| 465 | | ``\b`` | ASCII Backspace (BS) | | |
| 466 | +-----------------+---------------------------------+-------+ |
| 467 | | ``\f`` | ASCII Formfeed (FF) | | |
| 468 | +-----------------+---------------------------------+-------+ |
| 469 | | ``\n`` | ASCII Linefeed (LF) | | |
| 470 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 471 | | ``\r`` | ASCII Carriage Return (CR) | | |
| 472 | +-----------------+---------------------------------+-------+ |
| 473 | | ``\t`` | ASCII Horizontal Tab (TAB) | | |
| 474 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 475 | | ``\v`` | ASCII Vertical Tab (VT) | | |
| 476 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 477 | | ``\ooo`` | Character with octal value | (1,3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 478 | | | *ooo* | | |
| 479 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 480 | | ``\xhh`` | Character with hex value *hh* | (2,3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 481 | +-----------------+---------------------------------+-------+ |
| 482 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 483 | Escape sequences only recognized in string literals are: |
| 484 | |
| 485 | +-----------------+---------------------------------+-------+ |
| 486 | | Escape Sequence | Meaning | Notes | |
| 487 | +=================+=================================+=======+ |
| 488 | | ``\N{name}`` | Character named *name* in the | | |
| 489 | | | Unicode database | | |
| 490 | +-----------------+---------------------------------+-------+ |
| 491 | | ``\uxxxx`` | Character with 16-bit hex value | \(4) | |
| 492 | | | *xxxx* | | |
| 493 | +-----------------+---------------------------------+-------+ |
| 494 | | ``\Uxxxxxxxx`` | Character with 32-bit hex value | \(5) | |
| 495 | | | *xxxxxxxx* | | |
| 496 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 497 | |
| 498 | Notes: |
| 499 | |
| 500 | (1) |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 501 | As in Standard C, up to three octal digits are accepted. |
| 502 | |
| 503 | (2) |
| 504 | Unlike in Standard C, at most two hex digits are accepted. |
| 505 | |
| 506 | (3) |
| 507 | In a bytes literal, hexadecimal and octal escapes denote the byte with the |
| 508 | given value. In a string literal, these escapes denote a Unicode character |
| 509 | with the given value. |
| 510 | |
| 511 | (4) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 512 | Individual code units which form parts of a surrogate pair can be encoded using |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 513 | this escape sequence. Unlike in Standard C, exactly two hex digits are required. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 514 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 515 | (5) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 516 | Any Unicode character can be encoded this way, but characters outside the Basic |
| 517 | Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is |
| 518 | compiled to use 16-bit code units (the default). Individual code units which |
| 519 | form parts of a surrogate pair can be encoded using this escape sequence. |
| 520 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 521 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 522 | .. index:: unrecognized escape sequence |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 523 | |
| 524 | Unlike Standard C, all unrecognized escape sequences are left in the string |
| 525 | unchanged, i.e., *the backslash is left in the string*. (This behavior is |
| 526 | useful when debugging: if an escape sequence is mistyped, the resulting output |
| 527 | is more easily recognized as broken.) It is also important to note that the |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 528 | escape sequences only recognized in string literals fall into the category of |
| 529 | unrecognized escapes for bytes literals. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 530 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 531 | Even in a raw string, string quotes can be escaped with a backslash, but the |
| 532 | backslash remains in the string; for example, ``r"\""`` is a valid string |
| 533 | literal consisting of two characters: a backslash and a double quote; ``r"\"`` |
| 534 | is not a valid string literal (even a raw string cannot end in an odd number of |
| 535 | backslashes). Specifically, *a raw string cannot end in a single backslash* |
| 536 | (since the backslash would escape the following quote character). Note also |
| 537 | that a single backslash followed by a newline is interpreted as those two |
| 538 | characters as part of the string, *not* as a line continuation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 539 | |
| 540 | |
| 541 | .. _string-catenation: |
| 542 | |
| 543 | String literal concatenation |
| 544 | ---------------------------- |
| 545 | |
| 546 | Multiple adjacent string literals (delimited by whitespace), possibly using |
| 547 | different quoting conventions, are allowed, and their meaning is the same as |
| 548 | their concatenation. Thus, ``"hello" 'world'`` is equivalent to |
| 549 | ``"helloworld"``. This feature can be used to reduce the number of backslashes |
| 550 | needed, to split long strings conveniently across long lines, or even to add |
| 551 | comments to parts of strings, for example:: |
| 552 | |
| 553 | re.compile("[A-Za-z_]" # letter or underscore |
| 554 | "[A-Za-z0-9_]*" # letter, digit or underscore |
| 555 | ) |
| 556 | |
| 557 | Note that this feature is defined at the syntactical level, but implemented at |
| 558 | compile time. The '+' operator must be used to concatenate string expressions |
| 559 | at run time. Also note that literal concatenation can use different quoting |
| 560 | styles for each component (even mixing raw strings and triple quoted strings). |
| 561 | |
| 562 | |
| 563 | .. _numbers: |
| 564 | |
| 565 | Numeric literals |
| 566 | ---------------- |
| 567 | |
Georg Brandl | ba956ae | 2007-11-29 17:24:34 +0000 | [diff] [blame] | 568 | .. index:: number, numeric literal, integer literal |
| 569 | floating point literal, hexadecimal literal |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 570 | octal literal, binary literal, decimal literal, imaginary literal, complex literal |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 571 | |
Georg Brandl | 95817b3 | 2008-05-11 14:30:18 +0000 | [diff] [blame] | 572 | There are three types of numeric literals: integers, floating point numbers, and |
| 573 | imaginary numbers. There are no complex literals (complex numbers can be formed |
| 574 | by adding a real number and an imaginary number). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 575 | |
| 576 | Note that numeric literals do not include a sign; a phrase like ``-1`` is |
| 577 | actually an expression composed of the unary operator '``-``' and the literal |
| 578 | ``1``. |
| 579 | |
| 580 | |
| 581 | .. _integers: |
| 582 | |
| 583 | Integer literals |
| 584 | ---------------- |
| 585 | |
| 586 | Integer literals are described by the following lexical definitions: |
| 587 | |
| 588 | .. productionlist:: |
Georg Brandl | ddee308 | 2008-04-09 18:46:46 +0000 | [diff] [blame] | 589 | integer: `decimalinteger` | `octinteger` | `hexinteger` | `bininteger` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 590 | decimalinteger: `nonzerodigit` `digit`* | "0"+ |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 591 | nonzerodigit: "1"..."9" |
| 592 | digit: "0"..."9" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 593 | octinteger: "0" ("o" | "O") `octdigit`+ |
| 594 | hexinteger: "0" ("x" | "X") `hexdigit`+ |
| 595 | bininteger: "0" ("b" | "B") `bindigit`+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 596 | octdigit: "0"..."7" |
| 597 | hexdigit: `digit` | "a"..."f" | "A"..."F" |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 598 | bindigit: "0" | "1" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 599 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 600 | There is no limit for the length of integer literals apart from what can be |
| 601 | stored in available memory. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 602 | |
| 603 | Note that leading zeros in a non-zero decimal number are not allowed. This is |
| 604 | for disambiguation with C-style octal literals, which Python used before version |
| 605 | 3.0. |
| 606 | |
| 607 | Some examples of integer literals:: |
| 608 | |
| 609 | 7 2147483647 0o177 0b100110111 |
| 610 | 3 79228162514264337593543950336 0o377 0x100000000 |
Georg Brandl | 06788c9 | 2009-01-03 21:31:47 +0000 | [diff] [blame] | 611 | 79228162514264337593543950336 0xdeadbeef |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 612 | |
| 613 | |
| 614 | .. _floating: |
| 615 | |
| 616 | Floating point literals |
| 617 | ----------------------- |
| 618 | |
| 619 | Floating point literals are described by the following lexical definitions: |
| 620 | |
| 621 | .. productionlist:: |
| 622 | floatnumber: `pointfloat` | `exponentfloat` |
| 623 | pointfloat: [`intpart`] `fraction` | `intpart` "." |
| 624 | exponentfloat: (`intpart` | `pointfloat`) `exponent` |
| 625 | intpart: `digit`+ |
| 626 | fraction: "." `digit`+ |
| 627 | exponent: ("e" | "E") ["+" | "-"] `digit`+ |
| 628 | |
| 629 | Note that the integer and exponent parts are always interpreted using radix 10. |
| 630 | For example, ``077e010`` is legal, and denotes the same number as ``77e10``. The |
| 631 | allowed range of floating point literals is implementation-dependent. Some |
| 632 | examples of floating point literals:: |
| 633 | |
| 634 | 3.14 10. .001 1e100 3.14e-10 0e0 |
| 635 | |
| 636 | Note that numeric literals do not include a sign; a phrase like ``-1`` is |
| 637 | actually an expression composed of the unary operator ``-`` and the literal |
| 638 | ``1``. |
| 639 | |
| 640 | |
| 641 | .. _imaginary: |
| 642 | |
| 643 | Imaginary literals |
| 644 | ------------------ |
| 645 | |
| 646 | Imaginary literals are described by the following lexical definitions: |
| 647 | |
| 648 | .. productionlist:: |
| 649 | imagnumber: (`floatnumber` | `intpart`) ("j" | "J") |
| 650 | |
| 651 | An imaginary literal yields a complex number with a real part of 0.0. Complex |
| 652 | numbers are represented as a pair of floating point numbers and have the same |
| 653 | restrictions on their range. To create a complex number with a nonzero real |
| 654 | part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of |
| 655 | imaginary literals:: |
| 656 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 657 | 3.14j 10.j 10j .001j 1e100j 3.14e-10j |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 658 | |
| 659 | |
| 660 | .. _operators: |
| 661 | |
| 662 | Operators |
| 663 | ========= |
| 664 | |
| 665 | .. index:: single: operators |
| 666 | |
| 667 | The following tokens are operators:: |
| 668 | |
| 669 | + - * ** / // % |
| 670 | << >> & | ^ ~ |
| 671 | < > <= >= == != |
| 672 | |
| 673 | |
| 674 | .. _delimiters: |
| 675 | |
| 676 | Delimiters |
| 677 | ========== |
| 678 | |
| 679 | .. index:: single: delimiters |
| 680 | |
| 681 | The following tokens serve as delimiters in the grammar:: |
| 682 | |
Georg Brandl | 0df7979 | 2008-10-04 18:33:26 +0000 | [diff] [blame] | 683 | ( ) [ ] { } |
| 684 | , : . ; @ = |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 685 | += -= *= /= //= %= |
| 686 | &= |= ^= >>= <<= **= |
| 687 | |
| 688 | The period can also occur in floating-point and imaginary literals. A sequence |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 689 | of three periods has a special meaning as an ellipsis literal. The second half |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 690 | of the list, the augmented assignment operators, serve lexically as delimiters, |
| 691 | but also perform an operation. |
| 692 | |
| 693 | The following printing ASCII characters have special meaning as part of other |
| 694 | tokens or are otherwise significant to the lexical analyzer:: |
| 695 | |
| 696 | ' " # \ |
| 697 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 698 | The following printing ASCII characters are not used in Python. Their |
| 699 | occurrence outside string literals and comments is an unconditional error:: |
| 700 | |
| 701 | $ ? |