blob: 30677eaadce700160015a9ddce6a726c9e218026 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Éric Araujo29a0b572011-08-19 02:14:03 +02009**Source code:** :source:`Lib/tokenize.py`
10
11--------------
Georg Brandl8ec7f652007-08-15 14:28:01 +000012
13The :mod:`tokenize` module provides a lexical scanner for Python source code,
14implemented in Python. The scanner in this module returns comments as tokens as
15well, making it useful for implementing "pretty-printers," including colorizers
16for on-screen displays.
17
Georg Brandlcf3fb252007-10-21 10:52:38 +000018The primary entry point is a :term:`generator`:
Georg Brandl8ec7f652007-08-15 14:28:01 +000019
Georg Brandl8ec7f652007-08-15 14:28:01 +000020.. function:: generate_tokens(readline)
21
Georg Brandlebd662d2008-06-08 08:54:40 +000022 The :func:`generate_tokens` generator requires one argument, *readline*,
23 which must be a callable object which provides the same interface as the
Georg Brandl8ec7f652007-08-15 14:28:01 +000024 :meth:`readline` method of built-in file objects (see section
Georg Brandlebd662d2008-06-08 08:54:40 +000025 :ref:`bltin-file-objects`). Each call to the function should return one line
26 of input as a string.
Georg Brandl8ec7f652007-08-15 14:28:01 +000027
28 The generator produces 5-tuples with these members: the token type; the token
Georg Brandlebd662d2008-06-08 08:54:40 +000029 string; a 2-tuple ``(srow, scol)`` of ints specifying the row and column
30 where the token begins in the source; a 2-tuple ``(erow, ecol)`` of ints
31 specifying the row and column where the token ends in the source; and the
Georg Brandl3219df12008-06-08 08:59:38 +000032 line on which the token was found. The line passed (the last tuple item) is
33 the *logical* line; continuation lines are included.
Georg Brandl8ec7f652007-08-15 14:28:01 +000034
35 .. versionadded:: 2.2
36
37An older entry point is retained for backward compatibility:
38
39
40.. function:: tokenize(readline[, tokeneater])
41
42 The :func:`tokenize` function accepts two parameters: one representing the input
43 stream, and one providing an output mechanism for :func:`tokenize`.
44
45 The first parameter, *readline*, must be a callable object which provides the
46 same interface as the :meth:`readline` method of built-in file objects (see
47 section :ref:`bltin-file-objects`). Each call to the function should return one
48 line of input as a string. Alternately, *readline* may be a callable object that
49 signals completion by raising :exc:`StopIteration`.
50
51 .. versionchanged:: 2.5
52 Added :exc:`StopIteration` support.
53
54 The second parameter, *tokeneater*, must also be a callable object. It is
55 called once for each token, with five arguments, corresponding to the tuples
56 generated by :func:`generate_tokens`.
57
58All constants from the :mod:`token` module are also exported from
59:mod:`tokenize`, as are two additional token type values that might be passed to
60the *tokeneater* function by :func:`tokenize`:
61
62
63.. data:: COMMENT
64
65 Token value used to indicate a comment.
66
67
68.. data:: NL
69
70 Token value used to indicate a non-terminating newline. The NEWLINE token
71 indicates the end of a logical line of Python code; NL tokens are generated when
72 a logical line of code is continued over multiple physical lines.
73
74Another function is provided to reverse the tokenization process. This is useful
75for creating tools that tokenize a script, modify the token stream, and write
76back the modified script.
77
78
79.. function:: untokenize(iterable)
80
81 Converts tokens back into Python source code. The *iterable* must return
82 sequences with at least two elements, the token type and the token string. Any
83 additional sequence elements are ignored.
84
85 The reconstructed script is returned as a single string. The result is
86 guaranteed to tokenize back to match the input so that the conversion is
87 lossless and round-trips are assured. The guarantee applies only to the token
88 type and token string as the spacing between tokens (column positions) may
89 change.
90
91 .. versionadded:: 2.5
92
93Example of a script re-writer that transforms float literals into Decimal
94objects::
95
96 def decistmt(s):
97 """Substitute Decimals for floats in a string of statements.
98
99 >>> from decimal import Decimal
100 >>> s = 'print +21.3e-5*-.1234/81.7'
101 >>> decistmt(s)
102 "print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')"
103
104 >>> exec(s)
105 -3.21716034272e-007
106 >>> exec(decistmt(s))
107 -3.217160342717258261933904529E-7
108
109 """
110 result = []
111 g = generate_tokens(StringIO(s).readline) # tokenize the string
112 for toknum, tokval, _, _, _ in g:
113 if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens
114 result.extend([
115 (NAME, 'Decimal'),
116 (OP, '('),
117 (STRING, repr(tokval)),
118 (OP, ')')
119 ])
120 else:
121 result.append((toknum, tokval))
122 return untokenize(result)
123