blob: 577d7cca4c99cbb3996940d7fbae971b82cea803 [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
Raymond Hettinger10480942011-01-10 03:26:08 +00009**Source code:** :source:`Lib/tokenize.py`
Georg Brandl116aa622007-08-15 14:28:22 +000010
Raymond Hettinger4f707fd2011-01-10 19:54:11 +000011--------------
12
Georg Brandl116aa622007-08-15 14:28:22 +000013The :mod:`tokenize` module provides a lexical scanner for Python source code,
Trent Nelson428de652008-03-18 22:41:35 +000014implemented in Python. The scanner in this module returns comments as tokens
15as well, making it useful for implementing "pretty-printers," including
16colorizers for on-screen displays.
Georg Brandl116aa622007-08-15 14:28:22 +000017
Georg Brandl9afde1c2007-11-01 20:32:30 +000018The primary entry point is a :term:`generator`:
Georg Brandl116aa622007-08-15 14:28:22 +000019
Trent Nelson428de652008-03-18 22:41:35 +000020.. function:: tokenize(readline)
Georg Brandl116aa622007-08-15 14:28:22 +000021
Trent Nelson428de652008-03-18 22:41:35 +000022 The :func:`tokenize` generator requires one argument, *readline*, which
Georg Brandl116aa622007-08-15 14:28:22 +000023 must be a callable object which provides the same interface as the
Antoine Pitrou4adb2882010-01-04 18:50:53 +000024 :meth:`io.IOBase.readline` method of file objects. Each call to the
25 function should return one line of input as bytes.
Georg Brandl116aa622007-08-15 14:28:22 +000026
Georg Brandl48310cd2009-01-03 21:18:54 +000027 The generator produces 5-tuples with these members: the token type; the
28 token string; a 2-tuple ``(srow, scol)`` of ints specifying the row and
29 column where the token begins in the source; a 2-tuple ``(erow, ecol)`` of
30 ints specifying the row and column where the token ends in the source; and
Georg Brandlc28e1fa2008-06-10 19:20:26 +000031 the line on which the token was found. The line passed (the last tuple item)
Raymond Hettingera48db392009-04-29 00:34:27 +000032 is the *logical* line; continuation lines are included. The 5 tuple is
33 returned as a :term:`named tuple` with the field names:
34 ``type string start end line``.
35
36 .. versionchanged:: 3.1
37 Added support for named tuples.
Georg Brandl48310cd2009-01-03 21:18:54 +000038
Georg Brandlc28e1fa2008-06-10 19:20:26 +000039 :func:`tokenize` determines the source encoding of the file by looking for a
40 UTF-8 BOM or encoding cookie, according to :pep:`263`.
Georg Brandl116aa622007-08-15 14:28:22 +000041
Georg Brandl55ac8f02007-09-01 13:51:09 +000042
Georg Brandl116aa622007-08-15 14:28:22 +000043All constants from the :mod:`token` module are also exported from
Trent Nelson428de652008-03-18 22:41:35 +000044:mod:`tokenize`, as are three additional token type values:
Georg Brandl116aa622007-08-15 14:28:22 +000045
Georg Brandl116aa622007-08-15 14:28:22 +000046.. data:: COMMENT
47
48 Token value used to indicate a comment.
49
50
51.. data:: NL
52
53 Token value used to indicate a non-terminating newline. The NEWLINE token
Georg Brandl48310cd2009-01-03 21:18:54 +000054 indicates the end of a logical line of Python code; NL tokens are generated
Trent Nelson428de652008-03-18 22:41:35 +000055 when a logical line of code is continued over multiple physical lines.
Georg Brandl116aa622007-08-15 14:28:22 +000056
Trent Nelson428de652008-03-18 22:41:35 +000057
58.. data:: ENCODING
59
Georg Brandl48310cd2009-01-03 21:18:54 +000060 Token value that indicates the encoding used to decode the source bytes
61 into text. The first token returned by :func:`tokenize` will always be an
Trent Nelson428de652008-03-18 22:41:35 +000062 ENCODING token.
63
64
Georg Brandl48310cd2009-01-03 21:18:54 +000065Another function is provided to reverse the tokenization process. This is
66useful for creating tools that tokenize a script, modify the token stream, and
Trent Nelson428de652008-03-18 22:41:35 +000067write back the modified script.
Georg Brandl116aa622007-08-15 14:28:22 +000068
69
70.. function:: untokenize(iterable)
71
Trent Nelson428de652008-03-18 22:41:35 +000072 Converts tokens back into Python source code. The *iterable* must return
Georg Brandl48310cd2009-01-03 21:18:54 +000073 sequences with at least two elements, the token type and the token string.
Trent Nelson428de652008-03-18 22:41:35 +000074 Any additional sequence elements are ignored.
Georg Brandl48310cd2009-01-03 21:18:54 +000075
Trent Nelson428de652008-03-18 22:41:35 +000076 The reconstructed script is returned as a single string. The result is
77 guaranteed to tokenize back to match the input so that the conversion is
Georg Brandl48310cd2009-01-03 21:18:54 +000078 lossless and round-trips are assured. The guarantee applies only to the
79 token type and token string as the spacing between tokens (column
Trent Nelson428de652008-03-18 22:41:35 +000080 positions) may change.
Georg Brandl48310cd2009-01-03 21:18:54 +000081
82 It returns bytes, encoded using the ENCODING token, which is the first
Trent Nelson428de652008-03-18 22:41:35 +000083 token sequence output by :func:`tokenize`.
Georg Brandl116aa622007-08-15 14:28:22 +000084
Georg Brandl116aa622007-08-15 14:28:22 +000085
Trent Nelson428de652008-03-18 22:41:35 +000086:func:`tokenize` needs to detect the encoding of source files it tokenizes. The
87function it uses to do this is available:
88
89.. function:: detect_encoding(readline)
90
Georg Brandl48310cd2009-01-03 21:18:54 +000091 The :func:`detect_encoding` function is used to detect the encoding that
Georg Brandlae2dbe22009-03-13 19:04:40 +000092 should be used to decode a Python source file. It requires one argument,
Trent Nelson428de652008-03-18 22:41:35 +000093 readline, in the same way as the :func:`tokenize` generator.
Georg Brandl48310cd2009-01-03 21:18:54 +000094
Trent Nelson428de652008-03-18 22:41:35 +000095 It will call readline a maximum of twice, and return the encoding used
96 (as a string) and a list of any lines (not decoded from bytes) it has read
97 in.
Georg Brandl48310cd2009-01-03 21:18:54 +000098
Ezio Melottia8f6f1e2009-12-20 12:24:57 +000099 It detects the encoding from the presence of a UTF-8 BOM or an encoding
100 cookie as specified in :pep:`263`. If both a BOM and a cookie are present,
Benjamin Peterson689a5582010-03-18 22:29:52 +0000101 but disagree, a SyntaxError will be raised. Note that if the BOM is found,
102 ``'utf-8-sig'`` will be returned as an encoding.
Trent Nelson428de652008-03-18 22:41:35 +0000103
Benjamin Petersonb3a48292010-03-18 22:43:41 +0000104 If no encoding is specified, then the default of ``'utf-8'`` will be
105 returned.
106
Victor Stinner58c07522010-11-09 01:08:59 +0000107 Use :func:`open` to open Python source files: it uses
108 :func:`detect_encoding` to detect the file encoding.
Benjamin Petersonb3a48292010-03-18 22:43:41 +0000109
Victor Stinner58c07522010-11-09 01:08:59 +0000110
111.. function:: open(filename)
112
113 Open a file in read only mode using the encoding detected by
114 :func:`detect_encoding`.
115
116 .. versionadded:: 3.2
Georg Brandl48310cd2009-01-03 21:18:54 +0000117
118
Raymond Hettinger6c60d092010-09-09 04:32:39 +0000119Example of a script rewriter that transforms float literals into Decimal
Georg Brandl116aa622007-08-15 14:28:22 +0000120objects::
121
Ezio Melottia8f6f1e2009-12-20 12:24:57 +0000122 from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
123 from io import BytesIO
124
Trent Nelson428de652008-03-18 22:41:35 +0000125 def decistmt(s):
126 """Substitute Decimals for floats in a string of statements.
Georg Brandl48310cd2009-01-03 21:18:54 +0000127
Trent Nelson428de652008-03-18 22:41:35 +0000128 >>> from decimal import Decimal
129 >>> s = 'print(+21.3e-5*-.1234/81.7)'
130 >>> decistmt(s)
131 "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"
Georg Brandl48310cd2009-01-03 21:18:54 +0000132
Trent Nelson428de652008-03-18 22:41:35 +0000133 The format of the exponent is inherited from the platform C library.
134 Known cases are "e-007" (Windows) and "e-07" (not Windows). Since
135 we're only showing 12 digits, and the 13th isn't close to 5, the
136 rest of the output should be platform-independent.
Georg Brandl48310cd2009-01-03 21:18:54 +0000137
Trent Nelson428de652008-03-18 22:41:35 +0000138 >>> exec(s) #doctest: +ELLIPSIS
139 -3.21716034272e-0...7
Georg Brandl48310cd2009-01-03 21:18:54 +0000140
Trent Nelson428de652008-03-18 22:41:35 +0000141 Output from calculations with Decimal should be identical across all
142 platforms.
Georg Brandl48310cd2009-01-03 21:18:54 +0000143
Trent Nelson428de652008-03-18 22:41:35 +0000144 >>> exec(decistmt(s))
145 -3.217160342717258261933904529E-7
146 """
147 result = []
148 g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string
149 for toknum, tokval, _, _, _ in g:
150 if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens
151 result.extend([
152 (NAME, 'Decimal'),
153 (OP, '('),
154 (STRING, repr(tokval)),
155 (OP, ')')
156 ])
157 else:
158 result.append((toknum, tokval))
159 return untokenize(result).decode('utf-8')
Georg Brandl116aa622007-08-15 14:28:22 +0000160