blob: 7017045f618f45b2829212e62d7819f35eb5fa34 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`tokenize` --- Tokenizer for Python source
2===============================================
3
4.. module:: tokenize
5 :synopsis: Lexical scanner for Python source code.
6.. moduleauthor:: Ka Ping Yee
7.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8
9
10The :mod:`tokenize` module provides a lexical scanner for Python source code,
Trent Nelson428de652008-03-18 22:41:35 +000011implemented in Python. The scanner in this module returns comments as tokens
12as well, making it useful for implementing "pretty-printers," including
13colorizers for on-screen displays.
Georg Brandl116aa622007-08-15 14:28:22 +000014
Georg Brandl9afde1c2007-11-01 20:32:30 +000015The primary entry point is a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +000016
Trent Nelson428de652008-03-18 22:41:35 +000017.. function:: tokenize(readline)
Georg Brandl116aa622007-08-15 14:28:22 +000018
Trent Nelson428de652008-03-18 22:41:35 +000019 The :func:`tokenize` generator requires one argument, *readline*, which
Georg Brandl116aa622007-08-15 14:28:22 +000020 must be a callable object which provides the same interface as the
Antoine Pitroufa833952010-01-04 19:55:11 +000021 :meth:`io.IOBase.readline` method of file objects. Each call to the
22 function should return one line of input as bytes.
Georg Brandl116aa622007-08-15 14:28:22 +000023
Georg Brandl48310cd2009-01-03 21:18:54 +000024 The generator produces 5-tuples with these members: the token type; the
25 token string; a 2-tuple ``(srow, scol)`` of ints specifying the row and
26 column where the token begins in the source; a 2-tuple ``(erow, ecol)`` of
27 ints specifying the row and column where the token ends in the source; and
Georg Brandlc28e1fa2008-06-10 19:20:26 +000028 the line on which the token was found. The line passed (the last tuple item)
Raymond Hettingera48db392009-04-29 00:34:27 +000029 is the *logical* line; continuation lines are included. The 5 tuple is
30 returned as a :term:`named tuple` with the field names:
31 ``type string start end line``.
32
33 .. versionchanged:: 3.1
34 Added support for named tuples.
Georg Brandl48310cd2009-01-03 21:18:54 +000035
Georg Brandlc28e1fa2008-06-10 19:20:26 +000036 :func:`tokenize` determines the source encoding of the file by looking for a
37 UTF-8 BOM or encoding cookie, according to :pep:`263`.
Georg Brandl116aa622007-08-15 14:28:22 +000038
Georg Brandl55ac8f02007-09-01 13:51:09 +000039
Georg Brandl116aa622007-08-15 14:28:22 +000040All constants from the :mod:`token` module are also exported from
Trent Nelson428de652008-03-18 22:41:35 +000041:mod:`tokenize`, as are three additional token type values:
Georg Brandl116aa622007-08-15 14:28:22 +000042
Georg Brandl116aa622007-08-15 14:28:22 +000043.. data:: COMMENT
44
45 Token value used to indicate a comment.
46
47
48.. data:: NL
49
50 Token value used to indicate a non-terminating newline. The NEWLINE token
Georg Brandl48310cd2009-01-03 21:18:54 +000051 indicates the end of a logical line of Python code; NL tokens are generated
Trent Nelson428de652008-03-18 22:41:35 +000052 when a logical line of code is continued over multiple physical lines.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Trent Nelson428de652008-03-18 22:41:35 +000054
55.. data:: ENCODING
56
Georg Brandl48310cd2009-01-03 21:18:54 +000057 Token value that indicates the encoding used to decode the source bytes
58 into text. The first token returned by :func:`tokenize` will always be an
Trent Nelson428de652008-03-18 22:41:35 +000059 ENCODING token.
60
61
Georg Brandl48310cd2009-01-03 21:18:54 +000062Another function is provided to reverse the tokenization process. This is
63useful for creating tools that tokenize a script, modify the token stream, and
Trent Nelson428de652008-03-18 22:41:35 +000064write back the modified script.
Georg Brandl116aa622007-08-15 14:28:22 +000065
66
67.. function:: untokenize(iterable)
68
Trent Nelson428de652008-03-18 22:41:35 +000069 Converts tokens back into Python source code. The *iterable* must return
Georg Brandl48310cd2009-01-03 21:18:54 +000070 sequences with at least two elements, the token type and the token string.
Trent Nelson428de652008-03-18 22:41:35 +000071 Any additional sequence elements are ignored.
Georg Brandl48310cd2009-01-03 21:18:54 +000072
Trent Nelson428de652008-03-18 22:41:35 +000073 The reconstructed script is returned as a single string. The result is
74 guaranteed to tokenize back to match the input so that the conversion is
Georg Brandl48310cd2009-01-03 21:18:54 +000075 lossless and round-trips are assured. The guarantee applies only to the
76 token type and token string as the spacing between tokens (column
Trent Nelson428de652008-03-18 22:41:35 +000077 positions) may change.
Georg Brandl48310cd2009-01-03 21:18:54 +000078
79 It returns bytes, encoded using the ENCODING token, which is the first
Trent Nelson428de652008-03-18 22:41:35 +000080 token sequence output by :func:`tokenize`.
Georg Brandl116aa622007-08-15 14:28:22 +000081
Georg Brandl116aa622007-08-15 14:28:22 +000082
Trent Nelson428de652008-03-18 22:41:35 +000083:func:`tokenize` needs to detect the encoding of source files it tokenizes. The
84function it uses to do this is available:
85
86.. function:: detect_encoding(readline)
87
Georg Brandl48310cd2009-01-03 21:18:54 +000088 The :func:`detect_encoding` function is used to detect the encoding that
Georg Brandlae2dbe22009-03-13 19:04:40 +000089 should be used to decode a Python source file. It requires one argument,
Trent Nelson428de652008-03-18 22:41:35 +000090 readline, in the same way as the :func:`tokenize` generator.
Georg Brandl48310cd2009-01-03 21:18:54 +000091
Trent Nelson428de652008-03-18 22:41:35 +000092 It will call readline a maximum of twice, and return the encoding used
93 (as a string) and a list of any lines (not decoded from bytes) it has read
94 in.
Georg Brandl48310cd2009-01-03 21:18:54 +000095
Ezio Melottic5c8ff92009-12-20 12:26:45 +000096 It detects the encoding from the presence of a UTF-8 BOM or an encoding
97 cookie as specified in :pep:`263`. If both a BOM and a cookie are present,
Trent Nelson428de652008-03-18 22:41:35 +000098 but disagree, a SyntaxError will be raised.
Trent Nelson428de652008-03-18 22:41:35 +000099
Ezio Melottic5c8ff92009-12-20 12:26:45 +0000100 If no encoding is specified, then the default of ``'utf-8'`` will be returned.
Georg Brandl48310cd2009-01-03 21:18:54 +0000101
102
Georg Brandl116aa622007-08-15 14:28:22 +0000103Example of a script re-writer that transforms float literals into Decimal
104objects::
105
Ezio Melottic5c8ff92009-12-20 12:26:45 +0000106 from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
107 from io import BytesIO
108
Trent Nelson428de652008-03-18 22:41:35 +0000109 def decistmt(s):
110 """Substitute Decimals for floats in a string of statements.
Georg Brandl48310cd2009-01-03 21:18:54 +0000111
Trent Nelson428de652008-03-18 22:41:35 +0000112 >>> from decimal import Decimal
113 >>> s = 'print(+21.3e-5*-.1234/81.7)'
114 >>> decistmt(s)
115 "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"
Georg Brandl48310cd2009-01-03 21:18:54 +0000116
Trent Nelson428de652008-03-18 22:41:35 +0000117 The format of the exponent is inherited from the platform C library.
118 Known cases are "e-007" (Windows) and "e-07" (not Windows). Since
119 we're only showing 12 digits, and the 13th isn't close to 5, the
120 rest of the output should be platform-independent.
Georg Brandl48310cd2009-01-03 21:18:54 +0000121
Trent Nelson428de652008-03-18 22:41:35 +0000122 >>> exec(s) #doctest: +ELLIPSIS
123 -3.21716034272e-0...7
Georg Brandl48310cd2009-01-03 21:18:54 +0000124
Trent Nelson428de652008-03-18 22:41:35 +0000125 Output from calculations with Decimal should be identical across all
126 platforms.
Georg Brandl48310cd2009-01-03 21:18:54 +0000127
Trent Nelson428de652008-03-18 22:41:35 +0000128 >>> exec(decistmt(s))
129 -3.217160342717258261933904529E-7
130 """
131 result = []
132 g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string
133 for toknum, tokval, _, _, _ in g:
134 if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens
135 result.extend([
136 (NAME, 'Decimal'),
137 (OP, '('),
138 (STRING, repr(tokval)),
139 (OP, ')')
140 ])
141 else:
142 result.append((toknum, tokval))
143 return untokenize(result).decode('utf-8')
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Georg Brandl116aa622007-08-15 14:28:22 +0000145