blob: d66b07c62d43fe56cca4f61b23f7e896711cb119 [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
21 :meth:`readline` method of built-in file objects (see section
Georg Brandl48310cd2009-01-03 21:18:54 +000022 :ref:`bltin-file-objects`). Each call to the function should return one
Trent Nelson428de652008-03-18 22:41:35 +000023 line of input as bytes.
Georg Brandl116aa622007-08-15 14:28:22 +000024
Georg Brandl48310cd2009-01-03 21:18:54 +000025 The generator produces 5-tuples with these members: the token type; the
26 token string; a 2-tuple ``(srow, scol)`` of ints specifying the row and
27 column where the token begins in the source; a 2-tuple ``(erow, ecol)`` of
28 ints specifying the row and column where the token ends in the source; and
Georg Brandlc28e1fa2008-06-10 19:20:26 +000029 the line on which the token was found. The line passed (the last tuple item)
Raymond Hettingera48db392009-04-29 00:34:27 +000030 is the *logical* line; continuation lines are included. The 5 tuple is
31 returned as a :term:`named tuple` with the field names:
32 ``type string start end line``.
33
34 .. versionchanged:: 3.1
35 Added support for named tuples.
Georg Brandl48310cd2009-01-03 21:18:54 +000036
Georg Brandlc28e1fa2008-06-10 19:20:26 +000037 :func:`tokenize` determines the source encoding of the file by looking for a
38 UTF-8 BOM or encoding cookie, according to :pep:`263`.
Georg Brandl116aa622007-08-15 14:28:22 +000039
Georg Brandl55ac8f02007-09-01 13:51:09 +000040
Georg Brandl116aa622007-08-15 14:28:22 +000041All constants from the :mod:`token` module are also exported from
Trent Nelson428de652008-03-18 22:41:35 +000042:mod:`tokenize`, as are three additional token type values:
Georg Brandl116aa622007-08-15 14:28:22 +000043
Georg Brandl116aa622007-08-15 14:28:22 +000044.. data:: COMMENT
45
46 Token value used to indicate a comment.
47
48
49.. data:: NL
50
51 Token value used to indicate a non-terminating newline. The NEWLINE token
Georg Brandl48310cd2009-01-03 21:18:54 +000052 indicates the end of a logical line of Python code; NL tokens are generated
Trent Nelson428de652008-03-18 22:41:35 +000053 when a logical line of code is continued over multiple physical lines.
Georg Brandl116aa622007-08-15 14:28:22 +000054
Trent Nelson428de652008-03-18 22:41:35 +000055
56.. data:: ENCODING
57
Georg Brandl48310cd2009-01-03 21:18:54 +000058 Token value that indicates the encoding used to decode the source bytes
59 into text. The first token returned by :func:`tokenize` will always be an
Trent Nelson428de652008-03-18 22:41:35 +000060 ENCODING token.
61
62
Georg Brandl48310cd2009-01-03 21:18:54 +000063Another function is provided to reverse the tokenization process. This is
64useful for creating tools that tokenize a script, modify the token stream, and
Trent Nelson428de652008-03-18 22:41:35 +000065write back the modified script.
Georg Brandl116aa622007-08-15 14:28:22 +000066
67
68.. function:: untokenize(iterable)
69
Trent Nelson428de652008-03-18 22:41:35 +000070 Converts tokens back into Python source code. The *iterable* must return
Georg Brandl48310cd2009-01-03 21:18:54 +000071 sequences with at least two elements, the token type and the token string.
Trent Nelson428de652008-03-18 22:41:35 +000072 Any additional sequence elements are ignored.
Georg Brandl48310cd2009-01-03 21:18:54 +000073
Trent Nelson428de652008-03-18 22:41:35 +000074 The reconstructed script is returned as a single string. The result is
75 guaranteed to tokenize back to match the input so that the conversion is
Georg Brandl48310cd2009-01-03 21:18:54 +000076 lossless and round-trips are assured. The guarantee applies only to the
77 token type and token string as the spacing between tokens (column
Trent Nelson428de652008-03-18 22:41:35 +000078 positions) may change.
Georg Brandl48310cd2009-01-03 21:18:54 +000079
80 It returns bytes, encoded using the ENCODING token, which is the first
Trent Nelson428de652008-03-18 22:41:35 +000081 token sequence output by :func:`tokenize`.
Georg Brandl116aa622007-08-15 14:28:22 +000082
Georg Brandl116aa622007-08-15 14:28:22 +000083
Trent Nelson428de652008-03-18 22:41:35 +000084:func:`tokenize` needs to detect the encoding of source files it tokenizes. The
85function it uses to do this is available:
86
87.. function:: detect_encoding(readline)
88
Georg Brandl48310cd2009-01-03 21:18:54 +000089 The :func:`detect_encoding` function is used to detect the encoding that
Georg Brandlae2dbe22009-03-13 19:04:40 +000090 should be used to decode a Python source file. It requires one argument,
Trent Nelson428de652008-03-18 22:41:35 +000091 readline, in the same way as the :func:`tokenize` generator.
Georg Brandl48310cd2009-01-03 21:18:54 +000092
Trent Nelson428de652008-03-18 22:41:35 +000093 It will call readline a maximum of twice, and return the encoding used
94 (as a string) and a list of any lines (not decoded from bytes) it has read
95 in.
Georg Brandl48310cd2009-01-03 21:18:54 +000096
Ezio Melottia8f6f1e2009-12-20 12:24:57 +000097 It detects the encoding from the presence of a UTF-8 BOM or an encoding
98 cookie as specified in :pep:`263`. If both a BOM and a cookie are present,
Trent Nelson428de652008-03-18 22:41:35 +000099 but disagree, a SyntaxError will be raised.
Trent Nelson428de652008-03-18 22:41:35 +0000100
Ezio Melottia8f6f1e2009-12-20 12:24:57 +0000101 If no encoding is specified, then the default of ``'utf-8'`` will be returned.
Georg Brandl48310cd2009-01-03 21:18:54 +0000102
103
Georg Brandl116aa622007-08-15 14:28:22 +0000104Example of a script re-writer that transforms float literals into Decimal
105objects::
106
Ezio Melottia8f6f1e2009-12-20 12:24:57 +0000107 from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
108 from io import BytesIO
109
Trent Nelson428de652008-03-18 22:41:35 +0000110 def decistmt(s):
111 """Substitute Decimals for floats in a string of statements.
Georg Brandl48310cd2009-01-03 21:18:54 +0000112
Trent Nelson428de652008-03-18 22:41:35 +0000113 >>> from decimal import Decimal
114 >>> s = 'print(+21.3e-5*-.1234/81.7)'
115 >>> decistmt(s)
116 "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"
Georg Brandl48310cd2009-01-03 21:18:54 +0000117
Trent Nelson428de652008-03-18 22:41:35 +0000118 The format of the exponent is inherited from the platform C library.
119 Known cases are "e-007" (Windows) and "e-07" (not Windows). Since
120 we're only showing 12 digits, and the 13th isn't close to 5, the
121 rest of the output should be platform-independent.
Georg Brandl48310cd2009-01-03 21:18:54 +0000122
Trent Nelson428de652008-03-18 22:41:35 +0000123 >>> exec(s) #doctest: +ELLIPSIS
124 -3.21716034272e-0...7
Georg Brandl48310cd2009-01-03 21:18:54 +0000125
Trent Nelson428de652008-03-18 22:41:35 +0000126 Output from calculations with Decimal should be identical across all
127 platforms.
Georg Brandl48310cd2009-01-03 21:18:54 +0000128
Trent Nelson428de652008-03-18 22:41:35 +0000129 >>> exec(decistmt(s))
130 -3.217160342717258261933904529E-7
131 """
132 result = []
133 g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string
134 for toknum, tokval, _, _, _ in g:
135 if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens
136 result.extend([
137 (NAME, 'Decimal'),
138 (OP, '('),
139 (STRING, repr(tokval)),
140 (OP, ')')
141 ])
142 else:
143 result.append((toknum, tokval))
144 return untokenize(result).decode('utf-8')
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Georg Brandl116aa622007-08-15 14:28:22 +0000146