2. Análisis léxico — documentación de Python - 3.15.2
Navegación índice módulos | siguiente | anterior | Python » 3.15.2 documentation » Referencia del Lenguaje Python » 2. Análisis léxico | Tema | 2. Análisis léxico ¶ 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 produces these tokens. The lexical analyzer determines the program text’s encoding (UTF-8 by default), and decodes the text into source characters .
If the text cannot be decoded, a SyntaxError is raised. Next, the lexical analyzer uses the source characters to generate a stream of tokens. The type of a generated token generally depends on the next source character to be processed. Similarly, other special behavior of the analyzer depends on the first source character that hasn’t yet been processed. The following table gives a quick summary of these source characters, with links to sections that contain more information.
Character Next token (or other relevant documentation) espacio tabulador formfeed Whitespace CR, LF New line Indentation backslash ( \ ) Explicit line joining (Also significant in string escape sequences ) hash ( # ) Comment quote ( ' , " ) String literal ASCII letter ( a - z , A - Z ) non-ASCII character Name Prefixed string or bytes literal underscore ( _ ) Name (Can also be part of numeric literals ) number ( 0 - 9 ) Numeric literal dot ( . ) Numeric literal Operator question mark ( ? ) dollar ( $ ) backquote ( ` ) control character Error (outside string literals and comments) other printing character Operator or delimiter end of file End marker 2.1.
Estructura de línea ¶ Un programa Python se divide en un número de líneas lógicas . 2.1.1. Líneas lógicas ¶ 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. Líneas físicas ¶ A physical line is a sequence of characters terminated by one the following end-of-line sequences: the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), the “ Classic Mac OS ” form using the ASCII CR (return) character. Regardless of platform, each of these sequences is replaced by a single ASCII LF (linefeed) character. (This is done even inside string literals .) Each line can use any of the sequences; they do not need to be consistent within a file.
The end of input also serves as an implicit terminator for the final physical line. Formally: newline : <ASCII LF> | <ASCII CR> <ASCII LF> | <ASCII CR> 2.1.3. Comentarios ¶ Un comentario comienza con un carácter de almohadilla ( # ) que no es parte de un literal de cadena, y termina al final de la línea física. Un comentario implica el final de la línea lógica, a menos que se invoque la regla implícita de unión de líneas.
Los comentarios son ignorados por la sintaxis. 2.1.4. Declaración de Codificación ¶ Si un comentario en la primera o segunda línea del script de Python coincide con la expresión regular coding[=:]\s*([-\w.]+) , este comentario se procesa como una declaración de codificación; el primer grupo de esta expresión denomina la codificación del archivo de código fuente. La declaración de codificación debe aparecer en una línea propia.
Si se trata de la segunda línea, la primera línea debe ser también una línea solamente de comentario. Las formas recomendadas de una expresión de codificación son # -*- coding: <encoding-name> -*- que también es reconocido por GNU Emacs y # vim:fileencoding=<encoding-name> que es reconocido por el VIM de Bram Moolenaar. If no encoding declaration is found, the default encoding is UTF-8. If the implicit or explicit encoding of a file is UTF-8, an initial UTF-8 byte-order mark ( b'\xef\xbb\xbf' ) is ignored rather than being a syntax error.
Si se declara una codificación, Python debe reconocer el nombre de la codificación (ver Codificaciones estándar ). La codificación se utiliza para todos los análisis léxicos, incluidos las cadenas literales, los comentarios y los identificadores. All lexical analysis, including string literals, comments and identifiers, works on Unicode text decoded using the source encoding. Any Unicode code point, except the NUL control character, can appear in Python source. source_character : <any Unicode code point, except NUL> 2.1.5.
Unión explícita de líneas ¶ Dos o más líneas físicas pueden unirse en líneas lógicas utilizando caracteres de barra invertida ( \ ), de la siguiente manera: cuando una línea física termina en una barra invertida que no es parte de literal de cadena o de un comentario, se une con la siguiente formando una sola línea lógica, borrando la barra invertida y el siguiente carácter de fin de línea. Por ejemplo: 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 Una línea que termina en una barra invertida no puede llevar un comentario.
Una barra invertida no continúa un comentario. Una barra invertida no continúa un token excepto para los literales de la cadena (es decir, los tokens que no sean literales de la cadena no pueden ser divididos a través de líneas físicas usando una barra invertida). La barra invertida es ilegal en cualquier parte de una línea fuera del literal de la cadena. 2.1.6. Unión implícita de líneas ¶ Las expresiones entre paréntesis, entre corchetes o entre rizos pueden dividirse en más de una línea física sin usar barras invertidas.
Por ejemplo: month_names = [ 'Januari' , 'Februari' , 'Maart' , # Son los 'April' , 'Mei' , 'Juni' , # nombres holandeses 'Juli' , 'Augustus' , 'September' , # para los meses 'Oktober' , 'November' , 'December' ] # del año Las líneas continuas implícitas pueden llevar comentarios. La sangría de las líneas de continuación no es importante. Se permiten líneas de continuación en blanco. No hay ningún token NEWLINE (nueva línea) entre las líneas de continuación implícitas.
Las líneas de continuación implícitas también pueden aparecer dentro de cadenas de triple comilla ( ver más adelante); en ese caso no pueden llevar comentarios. 2.1.7. Líneas en blanco ¶ 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 (that is, one containing not even whitespace or a comment) terminates a multi-line statement. 2.1.8. Sangría ¶ El espacio en blanco ( espacios y tabulaciones) al principio de una línea lógica se utiliza para calcular el nivel de sangría de la línea, que a su vez se utiliza para determinar la agrupación de las declaraciones. Los tabuladores se sustituyen (de izquierda a derecha) por uno a ocho espacios, de manera que el número total de caracteres hasta el reemplazo inclusive es un múltiplo de ocho (se pretende que sea la misma regla que la utilizada por Unix).
El número total de espacios que preceden al primer carácter no en blanco determina entonces la sangría de la línea. La sangría no puede dividirse en múltiples líneas físicas utilizando barras invertidas; el espacio en blanco hasta la primera barra invertida determina la sangría. La indentación se rechaza como inconsistente si un archivo fuente mezcla tabulaciones y espacios de manera que el significado depende del valor de una tabulación en los espacios; un TabError se produce en ese caso.
Nota de compatibilidad entre plataformas: debido a l
The rest of this page is on the live site.