blob: d7ae6382e4e3d5784b6fd2dfa0ed29938c6e8ffd [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
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000015.. seealso::
16
17 Latest version of the :source:`tokenize module Python source code
18 <Lib/tokenize.py>`
19
Georg Brandl9afde1c2007-11-01 20:32:30 +000020The primary entry point is a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +000021
Trent Nelson428de652008-03-18 22:41:35 +000022.. function:: tokenize(readline)
Georg Brandl116aa622007-08-15 14:28:22 +000023
Trent Nelson428de652008-03-18 22:41:35 +000024 The :func:`tokenize` generator requires one argument, *readline*, which
Georg Brandl116aa622007-08-15 14:28:22 +000025 must be a callable object which provides the same interface as the
Antoine Pitrou4adb2882010-01-04 18:50:53 +000026 :meth:`io.IOBase.readline` method of file objects. Each call to the
27 function should return one line of input as bytes.
Georg Brandl116aa622007-08-15 14:28:22 +000028
Georg Brandl48310cd2009-01-03 21:18:54 +000029 The generator produces 5-tuples with these members: the token type; the
30 token string; a 2-tuple ``(srow, scol)`` of ints specifying the row and
31 column where the token begins in the source; a 2-tuple ``(erow, ecol)`` of
32 ints specifying the row and column where the token ends in the source; and
Georg Brandlc28e1fa2008-06-10 19:20:26 +000033 the line on which the token was found. The line passed (the last tuple item)
Raymond Hettingera48db392009-04-29 00:34:27 +000034 is the *logical* line; continuation lines are included. The 5 tuple is
35 returned as a :term:`named tuple` with the field names:
36 ``type string start end line``.
37
38 .. versionchanged:: 3.1
39 Added support for named tuples.
Georg Brandl48310cd2009-01-03 21:18:54 +000040
Georg Brandlc28e1fa2008-06-10 19:20:26 +000041 :func:`tokenize` determines the source encoding of the file by looking for a
42 UTF-8 BOM or encoding cookie, according to :pep:`263`.
Georg Brandl116aa622007-08-15 14:28:22 +000043
Georg Brandl55ac8f02007-09-01 13:51:09 +000044
Georg Brandl116aa622007-08-15 14:28:22 +000045All constants from the :mod:`token` module are also exported from
Trent Nelson428de652008-03-18 22:41:35 +000046:mod:`tokenize`, as are three additional token type values:
Georg Brandl116aa622007-08-15 14:28:22 +000047
Georg Brandl116aa622007-08-15 14:28:22 +000048.. data:: COMMENT
49
50 Token value used to indicate a comment.
51
52
53.. data:: NL
54
55 Token value used to indicate a non-terminating newline. The NEWLINE token
Georg Brandl48310cd2009-01-03 21:18:54 +000056 indicates the end of a logical line of Python code; NL tokens are generated
Trent Nelson428de652008-03-18 22:41:35 +000057 when a logical line of code is continued over multiple physical lines.
Georg Brandl116aa622007-08-15 14:28:22 +000058
Trent Nelson428de652008-03-18 22:41:35 +000059
60.. data:: ENCODING
61
Georg Brandl48310cd2009-01-03 21:18:54 +000062 Token value that indicates the encoding used to decode the source bytes
63 into text. The first token returned by :func:`tokenize` will always be an
Trent Nelson428de652008-03-18 22:41:35 +000064 ENCODING token.
65
66
Georg Brandl48310cd2009-01-03 21:18:54 +000067Another function is provided to reverse the tokenization process. This is
68useful for creating tools that tokenize a script, modify the token stream, and
Trent Nelson428de652008-03-18 22:41:35 +000069write back the modified script.
Georg Brandl116aa622007-08-15 14:28:22 +000070
71
72.. function:: untokenize(iterable)
73
Trent Nelson428de652008-03-18 22:41:35 +000074 Converts tokens back into Python source code. The *iterable* must return
Georg Brandl48310cd2009-01-03 21:18:54 +000075 sequences with at least two elements, the token type and the token string.
Trent Nelson428de652008-03-18 22:41:35 +000076 Any additional sequence elements are ignored.
Georg Brandl48310cd2009-01-03 21:18:54 +000077
Trent Nelson428de652008-03-18 22:41:35 +000078 The reconstructed script is returned as a single string. The result is
79 guaranteed to tokenize back to match the input so that the conversion is
Georg Brandl48310cd2009-01-03 21:18:54 +000080 lossless and round-trips are assured. The guarantee applies only to the
81 token type and token string as the spacing between tokens (column
Trent Nelson428de652008-03-18 22:41:35 +000082 positions) may change.
Georg Brandl48310cd2009-01-03 21:18:54 +000083
84 It returns bytes, encoded using the ENCODING token, which is the first
Trent Nelson428de652008-03-18 22:41:35 +000085 token sequence output by :func:`tokenize`.
Georg Brandl116aa622007-08-15 14:28:22 +000086
Georg Brandl116aa622007-08-15 14:28:22 +000087
Trent Nelson428de652008-03-18 22:41:35 +000088:func:`tokenize` needs to detect the encoding of source files it tokenizes. The
89function it uses to do this is available:
90
91.. function:: detect_encoding(readline)
92
Georg Brandl48310cd2009-01-03 21:18:54 +000093 The :func:`detect_encoding` function is used to detect the encoding that
Georg Brandlae2dbe22009-03-13 19:04:40 +000094 should be used to decode a Python source file. It requires one argument,
Trent Nelson428de652008-03-18 22:41:35 +000095 readline, in the same way as the :func:`tokenize` generator.
Georg Brandl48310cd2009-01-03 21:18:54 +000096
Trent Nelson428de652008-03-18 22:41:35 +000097 It will call readline a maximum of twice, and return the encoding used
98 (as a string) and a list of any lines (not decoded from bytes) it has read
99 in.
Georg Brandl48310cd2009-01-03 21:18:54 +0000100
Ezio Melottia8f6f1e2009-12-20 12:24:57 +0000101 It detects the encoding from the presence of a UTF-8 BOM or an encoding
102 cookie as specified in :pep:`263`. If both a BOM and a cookie are present,
Benjamin Peterson689a5582010-03-18 22:29:52 +0000103 but disagree, a SyntaxError will be raised. Note that if the BOM is found,
104 ``'utf-8-sig'`` will be returned as an encoding.
Trent Nelson428de652008-03-18 22:41:35 +0000105
Benjamin Petersonb3a48292010-03-18 22:43:41 +0000106 If no encoding is specified, then the default of ``'utf-8'`` will be
107 returned.
108
Victor Stinner58c07522010-11-09 01:08:59 +0000109 Use :func:`open` to open Python source files: it uses
110 :func:`detect_encoding` to detect the file encoding.
Benjamin Petersonb3a48292010-03-18 22:43:41 +0000111
Victor Stinner58c07522010-11-09 01:08:59 +0000112
113.. function:: open(filename)
114
115 Open a file in read only mode using the encoding detected by
116 :func:`detect_encoding`.
117
118 .. versionadded:: 3.2
Georg Brandl48310cd2009-01-03 21:18:54 +0000119
120
Raymond Hettinger6c60d092010-09-09 04:32:39 +0000121Example of a script rewriter that transforms float literals into Decimal
Georg Brandl116aa622007-08-15 14:28:22 +0000122objects::
123
Ezio Melottia8f6f1e2009-12-20 12:24:57 +0000124 from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
125 from io import BytesIO
126
Trent Nelson428de652008-03-18 22:41:35 +0000127 def decistmt(s):
128 """Substitute Decimals for floats in a string of statements.
Georg Brandl48310cd2009-01-03 21:18:54 +0000129
Trent Nelson428de652008-03-18 22:41:35 +0000130 >>> from decimal import Decimal
131 >>> s = 'print(+21.3e-5*-.1234/81.7)'
132 >>> decistmt(s)
133 "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"
Georg Brandl48310cd2009-01-03 21:18:54 +0000134
Trent Nelson428de652008-03-18 22:41:35 +0000135 The format of the exponent is inherited from the platform C library.
136 Known cases are "e-007" (Windows) and "e-07" (not Windows). Since
137 we're only showing 12 digits, and the 13th isn't close to 5, the
138 rest of the output should be platform-independent.
Georg Brandl48310cd2009-01-03 21:18:54 +0000139
Trent Nelson428de652008-03-18 22:41:35 +0000140 >>> exec(s) #doctest: +ELLIPSIS
141 -3.21716034272e-0...7
Georg Brandl48310cd2009-01-03 21:18:54 +0000142
Trent Nelson428de652008-03-18 22:41:35 +0000143 Output from calculations with Decimal should be identical across all
144 platforms.
Georg Brandl48310cd2009-01-03 21:18:54 +0000145
Trent Nelson428de652008-03-18 22:41:35 +0000146 >>> exec(decistmt(s))
147 -3.217160342717258261933904529E-7
148 """
149 result = []
150 g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string
151 for toknum, tokval, _, _, _ in g:
152 if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens
153 result.extend([
154 (NAME, 'Decimal'),
155 (OP, '('),
156 (STRING, repr(tokval)),
157 (OP, ')')
158 ])
159 else:
160 result.append((toknum, tokval))
161 return untokenize(result).decode('utf-8')
Georg Brandl116aa622007-08-15 14:28:22 +0000162