<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>30.7. tokenize — Tokenizer for Python source — Python v3.2.2 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '3.2.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python v3.2.2 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="top" title="Python v3.2.2 documentation" href="../index.html" /> <link rel="up" title="30. Python Language Services" href="language.html" /> <link rel="next" title="30.8. tabnanny — Detection of ambiguous indentation" href="tabnanny.html" /> <link rel="prev" title="30.6. keyword — Testing for Python keywords" href="keyword.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="tabnanny.html" title="30.8. tabnanny — Detection of ambiguous indentation" accesskey="N">next</a> |</li> <li class="right" > <a href="keyword.html" title="30.6. keyword — Testing for Python keywords" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="../index.html">Python v3.2.2 documentation</a> »</li> <li><a href="index.html" >The Python Standard Library</a> »</li> <li><a href="language.html" accesskey="U">30. Python Language Services</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="module-tokenize"> <span id="tokenize-tokenizer-for-python-source"></span><h1>30.7. <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-mod docutils literal"><span class="pre">tokenize</span></tt></a> — Tokenizer for Python source<a class="headerlink" href="#module-tokenize" title="Permalink to this headline">¶</a></h1> <p><strong>Source code:</strong> <a class="reference external" href="http://hg.python.org/cpython/file/3.2/Lib/tokenize.py">Lib/tokenize.py</a></p> <hr class="docutils" /> <p>The <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-mod docutils literal"><span class="pre">tokenize</span></tt></a> module provides a lexical scanner for Python source code, implemented in Python. The scanner in this module returns comments as tokens as well, making it useful for implementing “pretty-printers,” including colorizers for on-screen displays.</p> <p>The primary entry point is a <a class="reference internal" href="../glossary.html#term-generator"><em class="xref std std-term">generator</em></a>:</p> <dl class="function"> <dt id="tokenize.tokenize"> <tt class="descclassname">tokenize.</tt><tt class="descname">tokenize</tt><big>(</big><em>readline</em><big>)</big><a class="headerlink" href="#tokenize.tokenize" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-func docutils literal"><span class="pre">tokenize()</span></tt></a> generator requires one argument, <em>readline</em>, which must be a callable object which provides the same interface as the <a class="reference internal" href="io.html#io.IOBase.readline" title="io.IOBase.readline"><tt class="xref py py-meth docutils literal"><span class="pre">io.IOBase.readline()</span></tt></a> method of file objects. Each call to the function should return one line of input as bytes.</p> <p>The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple <tt class="docutils literal"><span class="pre">(srow,</span> <span class="pre">scol)</span></tt> of ints specifying the row and column where the token begins in the source; a 2-tuple <tt class="docutils literal"><span class="pre">(erow,</span> <span class="pre">ecol)</span></tt> of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the <em>logical</em> line; continuation lines are included. The 5 tuple is returned as a <a class="reference internal" href="../glossary.html#term-named-tuple"><em class="xref std std-term">named tuple</em></a> with the field names: <tt class="docutils literal"><span class="pre">type</span> <span class="pre">string</span> <span class="pre">start</span> <span class="pre">end</span> <span class="pre">line</span></tt>.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.1: </span>Added support for named tuples.</p> <p><a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-func docutils literal"><span class="pre">tokenize()</span></tt></a> determines the source encoding of the file by looking for a UTF-8 BOM or encoding cookie, according to <span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0263"><strong>PEP 263</strong></a>.</p> </dd></dl> <p>All constants from the <a class="reference internal" href="token.html#module-token" title="token: Constants representing terminal nodes of the parse tree."><tt class="xref py py-mod docutils literal"><span class="pre">token</span></tt></a> module are also exported from <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-mod docutils literal"><span class="pre">tokenize</span></tt></a>, as are three additional token type values:</p> <dl class="data"> <dt id="tokenize.COMMENT"> <tt class="descclassname">tokenize.</tt><tt class="descname">COMMENT</tt><a class="headerlink" href="#tokenize.COMMENT" title="Permalink to this definition">¶</a></dt> <dd><p>Token value used to indicate a comment.</p> </dd></dl> <dl class="data"> <dt id="tokenize.NL"> <tt class="descclassname">tokenize.</tt><tt class="descname">NL</tt><a class="headerlink" href="#tokenize.NL" title="Permalink to this definition">¶</a></dt> <dd><p>Token value used to indicate a non-terminating newline. The NEWLINE token indicates the end of a logical line of Python code; NL tokens are generated when a logical line of code is continued over multiple physical lines.</p> </dd></dl> <dl class="data"> <dt id="tokenize.ENCODING"> <tt class="descclassname">tokenize.</tt><tt class="descname">ENCODING</tt><a class="headerlink" href="#tokenize.ENCODING" title="Permalink to this definition">¶</a></dt> <dd><p>Token value that indicates the encoding used to decode the source bytes into text. The first token returned by <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-func docutils literal"><span class="pre">tokenize()</span></tt></a> will always be an ENCODING token.</p> </dd></dl> <p>Another function is provided to reverse the tokenization process. This is useful for creating tools that tokenize a script, modify the token stream, and write back the modified script.</p> <dl class="function"> <dt id="tokenize.untokenize"> <tt class="descclassname">tokenize.</tt><tt class="descname">untokenize</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#tokenize.untokenize" title="Permalink to this definition">¶</a></dt> <dd><p>Converts tokens back into Python source code. The <em>iterable</em> must return sequences with at least two elements, the token type and the token string. Any additional sequence elements are ignored.</p> <p>The reconstructed script is returned as a single string. The result is guaranteed to tokenize back to match the input so that the conversion is lossless and round-trips are assured. The guarantee applies only to the token type and token string as the spacing between tokens (column positions) may change.</p> <p>It returns bytes, encoded using the ENCODING token, which is the first token sequence output by <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-func docutils literal"><span class="pre">tokenize()</span></tt></a>.</p> </dd></dl> <p><a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-func docutils literal"><span class="pre">tokenize()</span></tt></a> needs to detect the encoding of source files it tokenizes. The function it uses to do this is available:</p> <dl class="function"> <dt id="tokenize.detect_encoding"> <tt class="descclassname">tokenize.</tt><tt class="descname">detect_encoding</tt><big>(</big><em>readline</em><big>)</big><a class="headerlink" href="#tokenize.detect_encoding" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="#tokenize.detect_encoding" title="tokenize.detect_encoding"><tt class="xref py py-func docutils literal"><span class="pre">detect_encoding()</span></tt></a> function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-func docutils literal"><span class="pre">tokenize()</span></tt></a> generator.</p> <p>It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (not decoded from bytes) it has read in.</p> <p>It detects the encoding from the presence of a UTF-8 BOM or an encoding cookie as specified in <span class="target" id="index-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0263"><strong>PEP 263</strong></a>. If both a BOM and a cookie are present, but disagree, a SyntaxError will be raised. Note that if the BOM is found, <tt class="docutils literal"><span class="pre">'utf-8-sig'</span></tt> will be returned as an encoding.</p> <p>If no encoding is specified, then the default of <tt class="docutils literal"><span class="pre">'utf-8'</span></tt> will be returned.</p> <p>Use <a class="reference internal" href="functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a> to open Python source files: it uses <a class="reference internal" href="#tokenize.detect_encoding" title="tokenize.detect_encoding"><tt class="xref py py-func docutils literal"><span class="pre">detect_encoding()</span></tt></a> to detect the file encoding.</p> </dd></dl> <dl class="function"> <dt id="tokenize.open"> <tt class="descclassname">tokenize.</tt><tt class="descname">open</tt><big>(</big><em>filename</em><big>)</big><a class="headerlink" href="#tokenize.open" title="Permalink to this definition">¶</a></dt> <dd><p>Open a file in read only mode using the encoding detected by <a class="reference internal" href="#tokenize.detect_encoding" title="tokenize.detect_encoding"><tt class="xref py py-func docutils literal"><span class="pre">detect_encoding()</span></tt></a>.</p> <p class="versionadded"> <span class="versionmodified">New in version 3.2.</span></p> </dd></dl> <p>Example of a script rewriter that transforms float literals into Decimal objects:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">tokenize</span> <span class="k">import</span> <span class="n">tokenize</span><span class="p">,</span> <span class="n">untokenize</span><span class="p">,</span> <span class="n">NUMBER</span><span class="p">,</span> <span class="n">STRING</span><span class="p">,</span> <span class="n">NAME</span><span class="p">,</span> <span class="n">OP</span> <span class="kn">from</span> <span class="nn">io</span> <span class="k">import</span> <span class="n">BytesIO</span> <span class="k">def</span> <span class="nf">decistmt</span><span class="p">(</span><span class="n">s</span><span class="p">):</span> <span class="sd">"""Substitute Decimals for floats in a string of statements.</span> <span class="sd"> >>> from decimal import Decimal</span> <span class="sd"> >>> s = 'print(+21.3e-5*-.1234/81.7)'</span> <span class="sd"> >>> decistmt(s)</span> <span class="sd"> "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"</span> <span class="sd"> The format of the exponent is inherited from the platform C library.</span> <span class="sd"> Known cases are "e-007" (Windows) and "e-07" (not Windows). Since</span> <span class="sd"> we're only showing 12 digits, and the 13th isn't close to 5, the</span> <span class="sd"> rest of the output should be platform-independent.</span> <span class="sd"> >>> exec(s) #doctest: +ELLIPSIS</span> <span class="sd"> -3.21716034272e-0...7</span> <span class="sd"> Output from calculations with Decimal should be identical across all</span> <span class="sd"> platforms.</span> <span class="sd"> >>> exec(decistmt(s))</span> <span class="sd"> -3.217160342717258261933904529E-7</span> <span class="sd"> """</span> <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span> <span class="n">g</span> <span class="o">=</span> <span class="n">tokenize</span><span class="p">(</span><span class="n">BytesIO</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s">'utf-8'</span><span class="p">))</span><span class="o">.</span><span class="n">readline</span><span class="p">)</span> <span class="c"># tokenize the string</span> <span class="k">for</span> <span class="n">toknum</span><span class="p">,</span> <span class="n">tokval</span><span class="p">,</span> <span class="n">_</span><span class="p">,</span> <span class="n">_</span><span class="p">,</span> <span class="n">_</span> <span class="ow">in</span> <span class="n">g</span><span class="p">:</span> <span class="k">if</span> <span class="n">toknum</span> <span class="o">==</span> <span class="n">NUMBER</span> <span class="ow">and</span> <span class="s">'.'</span> <span class="ow">in</span> <span class="n">tokval</span><span class="p">:</span> <span class="c"># replace NUMBER tokens</span> <span class="n">result</span><span class="o">.</span><span class="n">extend</span><span class="p">([</span> <span class="p">(</span><span class="n">NAME</span><span class="p">,</span> <span class="s">'Decimal'</span><span class="p">),</span> <span class="p">(</span><span class="n">OP</span><span class="p">,</span> <span class="s">'('</span><span class="p">),</span> <span class="p">(</span><span class="n">STRING</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">tokval</span><span class="p">)),</span> <span class="p">(</span><span class="n">OP</span><span class="p">,</span> <span class="s">')'</span><span class="p">)</span> <span class="p">])</span> <span class="k">else</span><span class="p">:</span> <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">toknum</span><span class="p">,</span> <span class="n">tokval</span><span class="p">))</span> <span class="k">return</span> <span class="n">untokenize</span><span class="p">(</span><span class="n">result</span><span class="p">)</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s">'utf-8'</span><span class="p">)</span> </pre></div> </div> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="keyword.html" title="previous chapter">30.6. <tt class="docutils literal docutils literal docutils literal"><span class="pre">keyword</span></tt> — Testing for Python keywords</a></p> <h4>Next topic</h4> <p class="topless"><a href="tabnanny.html" title="next chapter">30.8. <tt class="docutils literal docutils literal docutils literal"><span class="pre">tabnanny</span></tt> — Detection of ambiguous indentation</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li><a href="../_sources/library/tokenize.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" size="18" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="tabnanny.html" title="30.8. tabnanny — Detection of ambiguous indentation" >next</a> |</li> <li class="right" > <a href="keyword.html" title="30.6. keyword — Testing for Python keywords" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="../index.html">Python v3.2.2 documentation</a> »</li> <li><a href="index.html" >The Python Standard Library</a> »</li> <li><a href="language.html" >30. Python Language Services</a> »</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 1990-2011, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="http://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Sep 04, 2011. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7. </div> </body> </html>