blob: 446d3bbde985fa7bb8d80fe3701d38a9cee4ca32 [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 Pitrou4adb2882010-01-04 18:50:53 +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 Melottia8f6f1e2009-12-20 12:24:57 +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,
Benjamin Peterson689a5582010-03-18 22:29:52 +000098 but disagree, a SyntaxError will be raised. Note that if the BOM is found,
99 ``'utf-8-sig'`` will be returned as an encoding.
Trent Nelson428de652008-03-18 22:41:35 +0000100
Benjamin Petersonb3a48292010-03-18 22:43:41 +0000101 If no encoding is specified, then the default of ``'utf-8'`` will be
102 returned.
103
104 :func:`detect_encoding` is useful for robustly reading Python source files.
105 A common pattern for this follows::
106
107 def read_python_source(file_name):
108 with open(file_name, "rb") as fp:
109 encoding = tokenize.detect_encoding(fp.readline)[0]
110 with open(file_name, "r", encoding=encoding) as fp:
111 return fp.read()
Georg Brandl48310cd2009-01-03 21:18:54 +0000112
113
Georg Brandl116aa622007-08-15 14:28:22 +0000114Example of a script re-writer that transforms float literals into Decimal
115objects::
116
Ezio Melottia8f6f1e2009-12-20 12:24:57 +0000117 from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
118 from io import BytesIO
119
Trent Nelson428de652008-03-18 22:41:35 +0000120 def decistmt(s):
121 """Substitute Decimals for floats in a string of statements.
Georg Brandl48310cd2009-01-03 21:18:54 +0000122
Trent Nelson428de652008-03-18 22:41:35 +0000123 >>> from decimal import Decimal
124 >>> s = 'print(+21.3e-5*-.1234/81.7)'
125 >>> decistmt(s)
126 "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"
Georg Brandl48310cd2009-01-03 21:18:54 +0000127
Trent Nelson428de652008-03-18 22:41:35 +0000128 The format of the exponent is inherited from the platform C library.
129 Known cases are "e-007" (Windows) and "e-07" (not Windows). Since
130 we're only showing 12 digits, and the 13th isn't close to 5, the
131 rest of the output should be platform-independent.
Georg Brandl48310cd2009-01-03 21:18:54 +0000132
Trent Nelson428de652008-03-18 22:41:35 +0000133 >>> exec(s) #doctest: +ELLIPSIS
134 -3.21716034272e-0...7
Georg Brandl48310cd2009-01-03 21:18:54 +0000135
Trent Nelson428de652008-03-18 22:41:35 +0000136 Output from calculations with Decimal should be identical across all
137 platforms.
Georg Brandl48310cd2009-01-03 21:18:54 +0000138
Trent Nelson428de652008-03-18 22:41:35 +0000139 >>> exec(decistmt(s))
140 -3.217160342717258261933904529E-7
141 """
142 result = []
143 g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string
144 for toknum, tokval, _, _, _ in g:
145 if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens
146 result.extend([
147 (NAME, 'Decimal'),
148 (OP, '('),
149 (STRING, repr(tokval)),
150 (OP, ')')
151 ])
152 else:
153 result.append((toknum, tokval))
154 return untokenize(result).decode('utf-8')
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Georg Brandl116aa622007-08-15 14:28:22 +0000156