parthtamu/rag-code-assistant
0
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4 <head>5 <meta charset="utf-8" />6 <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="tokenize — Tokenizer for Python source" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/tokenize.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/tokenize.py The tokenize 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 u..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_tokenize_98863b6b.png" />15<meta property="og:image:alt" content="Source code: Lib/tokenize.py The tokenize 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 u..." />16<meta name="description" content="Source code: Lib/tokenize.py The tokenize 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 u..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20 <title>tokenize — Tokenizer for Python source — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21 22 <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23 <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24 <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25 <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26 <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27 28 <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29 <script src="../_static/doctools.js?v=9bcbadda"></script>30 <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31 <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32 33 <script src="../_static/sidebar.js"></script>34 35 <link rel="search" type="application/opensearchdescription+xml"36 title="Search within Python 3.15.0a6 documentation"37 href="../_static/opensearch.xml"/>38 <link rel="author" title="About these documents" href="../about.html" />39 <link rel="index" title="Index" href="../genindex.html" />40 <link rel="search" title="Search" href="../search.html" />41 <link rel="copyright" title="Copyright" href="../copyright.html" />42 <link rel="next" title="tabnanny — Detection of ambiguous indentation" href="tabnanny.html" />43 <link rel="prev" title="keyword — Testing for Python keywords" href="keyword.html" />44 45 46 <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47 48 <link rel="canonical" href="https://docs.python.org/3/library/tokenize.html">49 50 51 52 53 <style>54 @media only screen {55 table.full-width-table {56 width: 100%;57 }58 }59 </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61 <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62 <script type="text/javascript" src="../_static/copybutton.js"></script>63 <script type="text/javascript" src="../_static/menu.js"></script>64 <script type="text/javascript" src="../_static/search-focus.js"></script>65 <script type="text/javascript" src="../_static/themetoggle.js"></script> 66 <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67 <meta name="readthedocs-addons-api-version" content="1">68 69 </head>70<body>71<div class="mobile-nav">72 <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73 aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74 <nav class="nav-content" role="navigation">75 <label for="menuToggler" class="toggler__label">76 <span></span>77 </label>78 <span class="nav-items-wrapper">79 <a href="https://www.python.org/" class="nav-logo">80 <img src="../_static/py.svg" alt="Python logo">81 </a>82 <span class="version_switcher_placeholder"></span>83 <form role="search" class="search" action="../search.html" method="get">84 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85 <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86 </svg>87 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88 <input type="submit" value="Go">89 </form>90 </span>91 </nav>92 <div class="menu-wrapper">93 <nav class="menu" role="navigation" aria-label="main navigation">94 <div class="language_switcher_placeholder"></div>95 96<label class="theme-selector-label">97 Theme98 <select class="theme-selector" oninput="activateTheme(this.value)">99 <option value="auto" selected>Auto</option>100 <option value="light">Light</option>101 <option value="dark">Dark</option>102 </select>103</label>104 <div>105 <h3><a href="../contents.html">Table of Contents</a></h3>106 <ul>107<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source</a><ul>108<li><a class="reference internal" href="#tokenizing-input">Tokenizing Input</a></li>109<li><a class="reference internal" href="#command-line-usage">Command-Line Usage</a></li>110<li><a class="reference internal" href="#examples">Examples</a></li>111</ul>112</li>113</ul>114 115 </div>116 <div>117 <h4>Previous topic</h4>118 <p class="topless"><a href="keyword.html"119 title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">keyword</span></code> — Testing for Python keywords</a></p>120 </div>121 <div>122 <h4>Next topic</h4>123 <p class="topless"><a href="tabnanny.html"124 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tabnanny</span></code> — Detection of ambiguous indentation</a></p>125 </div>126 <script>127 document.addEventListener('DOMContentLoaded', () => {128 const title = document.querySelector('meta[property="og:title"]').content;129 const elements = document.querySelectorAll('.improvepage');130 const pageurl = window.location.href.split('?')[0];131 elements.forEach(element => {132 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));133 url.searchParams.set('pagetitle', title);134 url.searchParams.set('pageurl', pageurl);135 url.searchParams.set('pagesource', "library/tokenize.rst");136 element.href = url.toString();137 });138 });139 </script>140 <div role="note" aria-label="source link">141 <h3>This page</h3>142 <ul class="this-page-menu">143 <li><a href="../bugs.html">Report a bug</a></li>144 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>145 <li>146 <a href="https://github.com/python/cpython/blob/main/Doc/library/tokenize.rst?plain=1"147 rel="nofollow">Show source148 </a>149 </li>150 151 </ul>152 </div>153 </nav>154 </div>155</div>156 157 158 <div class="related" role="navigation" aria-label="Related">159 <h3>Navigation</h3>160 <ul>161 <li class="right" style="margin-right: 10px">162 <a href="../genindex.html" title="General Index"163 accesskey="I">index</a></li>164 <li class="right" >165 <a href="../py-modindex.html" title="Python Module Index"166 >modules</a> |</li>167 <li class="right" >168 <a href="tabnanny.html" title="tabnanny — Detection of ambiguous indentation"169 accesskey="N">next</a> |</li>170 <li class="right" >171 <a href="keyword.html" title="keyword — Testing for Python keywords"172 accesskey="P">previous</a> |</li>173 174 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>175 <li><a href="https://www.python.org/">Python</a> »</li>176 <li class="switchers">177 <div class="language_switcher_placeholder"></div>178 <div class="version_switcher_placeholder"></div>179 </li>180 <li>181 182 </li>183 <li id="cpython-language-and-version">184 <a href="../index.html">3.15.0a6 Documentation</a> »185 </li>186 187 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>188 <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">Python Language Services</a> »</li>189 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source</a></li>190 <li class="right">191 192 193 <div class="inline-search" role="search">194 <form class="inline-search" action="../search.html" method="get">195 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">196 <input type="submit" value="Go">197 </form>198 </div>199 |200 </li>201 <li class="right">202<label class="theme-selector-label">203 Theme204 <select class="theme-selector" oninput="activateTheme(this.value)">205 <option value="auto" selected>Auto</option>206 <option value="light">Light</option>207 <option value="dark">Dark</option>208 </select>209</label> |</li>210 211 </ul>212 </div> 213 214 <div class="document">215 <div class="documentwrapper">216 <div class="bodywrapper">217 <div class="body" role="main">218 219 <section id="module-tokenize">220<span id="tokenize-tokenizer-for-python-source"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source<a class="headerlink" href="#module-tokenize" title="Link to this heading">¶</a></h1>221<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/tokenize.py">Lib/tokenize.py</a></p>222<hr class="docutils" />223<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code> module provides a lexical scanner for Python source code,224implemented in Python. The scanner in this module returns comments as tokens225as well, making it useful for implementing “pretty-printers”, including226colorizers for on-screen displays.</p>227<p>To simplify token stream handling, all <a class="reference internal" href="../reference/lexical_analysis.html#operators"><span class="std std-ref">operator</span></a> and228<a class="reference internal" href="../reference/lexical_analysis.html#delimiters"><span class="std std-ref">delimiter</span></a> tokens and <a class="reference internal" href="constants.html#Ellipsis" title="Ellipsis"><code class="xref py py-data docutils literal notranslate"><span class="pre">Ellipsis</span></code></a> are returned using229the generic <a class="reference internal" href="token.html#token.OP" title="token.OP"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP</span></code></a> token type. The exact230type can be determined by checking the <code class="docutils literal notranslate"><span class="pre">exact_type</span></code> property on the231<a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> returned from <a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize.tokenize()</span></code></a>.</p>232<div class="admonition warning">233<p class="admonition-title">Warning</p>234<p>Note that the functions in this module are only designed to parse235syntactically valid Python code (code that does not raise when parsed236using <a class="reference internal" href="ast.html#ast.parse" title="ast.parse"><code class="xref py py-func docutils literal notranslate"><span class="pre">ast.parse()</span></code></a>). The behavior of the functions in this module is237<strong>undefined</strong> when providing invalid Python code and it can change at any238point.</p>239</div>240<section id="tokenizing-input">241<h2>Tokenizing Input<a class="headerlink" href="#tokenizing-input" title="Link to this heading">¶</a></h2>242<p>The primary entry point is a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>:</p>243<dl class="py function">244<dt class="sig sig-object py" id="tokenize.tokenize">245<span class="sig-prename descclassname"><span class="pre">tokenize.</span></span><span class="sig-name descname"><span class="pre">tokenize</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">readline</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tokenize.tokenize" title="Link to this definition">¶</a></dt>246<dd><p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code> generator requires one argument, <em>readline</em>, which247must be a callable object which provides the same interface as the248<a class="reference internal" href="io.html#io.IOBase.readline" title="io.IOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">io.IOBase.readline()</span></code></a> method of file objects. Each call to the249function should return one line of input as bytes.</p>250<p>The generator produces 5-tuples with these members: the token type; the251token string; a 2-tuple <code class="docutils literal notranslate"><span class="pre">(srow,</span> <span class="pre">scol)</span></code> of ints specifying the row and252column where the token begins in the source; a 2-tuple <code class="docutils literal notranslate"><span class="pre">(erow,</span> <span class="pre">ecol)</span></code> of253ints specifying the row and column where the token ends in the source; and254the line on which the token was found. The line passed (the last tuple item)255is the <em>physical</em> line. The 5 tuple is returned as a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a>256with the field names:257<code class="docutils literal notranslate"><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></code>.</p>258<p>The returned <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> has an additional property named259<code class="docutils literal notranslate"><span class="pre">exact_type</span></code> that contains the exact operator type for260<a class="reference internal" href="token.html#token.OP" title="token.OP"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP</span></code></a> tokens. For all other token types <code class="docutils literal notranslate"><span class="pre">exact_type</span></code>261equals the named tuple <code class="docutils literal notranslate"><span class="pre">type</span></code> field.</p>262<div class="versionchanged">263<p><span class="versionmodified changed">Changed in version 3.1: </span>Added support for named tuples.</p>264</div>265<div class="versionchanged">266<p><span class="versionmodified changed">Changed in version 3.3: </span>Added support for <code class="docutils literal notranslate"><span class="pre">exact_type</span></code>.</p>267</div>268<p><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code> determines the source encoding of the file by looking for a269UTF-8 BOM or encoding cookie, according to <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0263/"><strong>PEP 263</strong></a>.</p>270</dd></dl>271 272<dl class="py function">273<dt class="sig sig-object py" id="tokenize.generate_tokens">274<span class="sig-prename descclassname"><span class="pre">tokenize.</span></span><span class="sig-name descname"><span class="pre">generate_tokens</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">readline</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tokenize.generate_tokens" title="Link to this definition">¶</a></dt>275<dd><p>Tokenize a source reading unicode strings instead of bytes.</p>276<p>Like <a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code></a>, the <em>readline</em> argument is a callable returning277a single line of input. However, <code class="xref py py-func docutils literal notranslate"><span class="pre">generate_tokens()</span></code> expects <em>readline</em>278to return a str object rather than bytes.</p>279<p>The result is an iterator yielding named tuples, exactly like280<a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code></a>. It does not yield an <a class="reference internal" href="token.html#token.ENCODING" title="token.ENCODING"><code class="xref py py-data docutils literal notranslate"><span class="pre">ENCODING</span></code></a> token.</p>281</dd></dl>282 283<p>All constants from the <a class="reference internal" href="token.html#module-token" title="token: Constants representing terminal nodes of the parse tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">token</span></code></a> module are also exported from284<code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code>.</p>285<p>Another function is provided to reverse the tokenization process. This is286useful for creating tools that tokenize a script, modify the token stream, and287write back the modified script.</p>288<dl class="py function">289<dt class="sig sig-object py" id="tokenize.untokenize">290<span class="sig-prename descclassname"><span class="pre">tokenize.</span></span><span class="sig-name descname"><span class="pre">untokenize</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">iterable</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tokenize.untokenize" title="Link to this definition">¶</a></dt>291<dd><p>Converts tokens back into Python source code. The <em>iterable</em> must return292sequences with at least two elements, the token type and the token string.293Any additional sequence elements are ignored.</p>294<p>The result is guaranteed to tokenize back to match the input so that the295conversion is lossless and round-trips are assured. The guarantee applies296only to the token type and token string as the spacing between tokens297(column positions) may change.</p>298<p>It returns bytes, encoded using the <a class="reference internal" href="token.html#token.ENCODING" title="token.ENCODING"><code class="xref py py-data docutils literal notranslate"><span class="pre">ENCODING</span></code></a> token, which299is the first token sequence output by <a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code></a>. If there is no300encoding token in the input, it returns a str instead.</p>301</dd></dl>302 303<p><a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code></a> needs to detect the encoding of source files it tokenizes. The304function it uses to do this is available:</p>305<dl class="py function">306<dt class="sig sig-object py" id="tokenize.detect_encoding">307<span class="sig-prename descclassname"><span class="pre">tokenize.</span></span><span class="sig-name descname"><span class="pre">detect_encoding</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">readline</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tokenize.detect_encoding" title="Link to this definition">¶</a></dt>308<dd><p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">detect_encoding()</span></code> function is used to detect the encoding that309should be used to decode a Python source file. It requires one argument,310readline, in the same way as the <a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code></a> generator.</p>311<p>It will call readline a maximum of twice, and return the encoding used312(as a string) and a list of any lines (not decoded from bytes) it has read313in.</p>314<p>It detects the encoding from the presence of a UTF-8 BOM or an encoding315cookie as specified in <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0263/"><strong>PEP 263</strong></a>. If both a BOM and a cookie are present,316but disagree, a <a class="reference internal" href="exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> will be raised. Note that if the BOM is found,317<code class="docutils literal notranslate"><span class="pre">'utf-8-sig'</span></code> will be returned as an encoding.</p>318<p>If no encoding is specified, then the default of <code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code> will be319returned.</p>320<p>Use <a class="reference internal" href="#tokenize.open" title="tokenize.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> to open Python source files: it uses321<code class="xref py py-func docutils literal notranslate"><span class="pre">detect_encoding()</span></code> to detect the file encoding.</p>322</dd></dl>323 324<dl class="py function">325<dt class="sig sig-object py" id="tokenize.open">326<span class="sig-prename descclassname"><span class="pre">tokenize.</span></span><span class="sig-name descname"><span class="pre">open</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">filename</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tokenize.open" title="Link to this definition">¶</a></dt>327<dd><p>Open a file in read only mode using the encoding detected by328<a class="reference internal" href="#tokenize.detect_encoding" title="tokenize.detect_encoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">detect_encoding()</span></code></a>.</p>329<div class="versionadded">330<p><span class="versionmodified added">Added in version 3.2.</span></p>331</div>332</dd></dl>333 334<dl class="py exception">335<dt class="sig sig-object py" id="tokenize.TokenError">336<em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">tokenize.</span></span><span class="sig-name descname"><span class="pre">TokenError</span></span><a class="headerlink" href="#tokenize.TokenError" title="Link to this definition">¶</a></dt>337<dd><p>Raised when either a docstring or expression that may be split over several338lines is not completed anywhere in the file, for example:</p>339<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="s2">"""Beginning of</span>340<span class="s2">docstring</span>341</pre></div>342</div>343<p>or:</p>344<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="mi">1</span><span class="p">,</span>345 <span class="mi">2</span><span class="p">,</span>346 <span class="mi">3</span>347</pre></div>348</div>349</dd></dl>350 351</section>352<section id="command-line-usage">353<span id="tokenize-cli"></span><h2>Command-Line Usage<a class="headerlink" href="#command-line-usage" title="Link to this heading">¶</a></h2>354<div class="versionadded">355<p><span class="versionmodified added">Added in version 3.3.</span></p>356</div>357<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code> module can be executed as a script from the command line.358It is as simple as:</p>359<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>python<span class="w"> </span>-m<span class="w"> </span>tokenize<span class="w"> </span><span class="o">[</span>-e<span class="o">]</span><span class="w"> </span><span class="o">[</span>filename.py<span class="o">]</span>360</pre></div>361</div>362<p>The following options are accepted:</p>363<dl class="std option">364<dt class="sig sig-object std" id="cmdoption-tokenize-h">365<span id="cmdoption-tokenize-help"></span><span class="sig-name descname"><span class="pre">-h</span></span><span class="sig-prename descclassname"></span><span class="sig-prename descclassname"><span class="pre">,</span> </span><span class="sig-name descname"><span class="pre">--help</span></span><span class="sig-prename descclassname"></span><a class="headerlink" href="#cmdoption-tokenize-h" title="Link to this definition">¶</a></dt>366<dd><p>show this help message and exit</p>367</dd></dl>368 369<dl class="std option">370<dt class="sig sig-object std" id="cmdoption-tokenize-e">371<span id="cmdoption-tokenize-exact"></span><span class="sig-name descname"><span class="pre">-e</span></span><span class="sig-prename descclassname"></span><span class="sig-prename descclassname"><span class="pre">,</span> </span><span class="sig-name descname"><span class="pre">--exact</span></span><span class="sig-prename descclassname"></span><a class="headerlink" href="#cmdoption-tokenize-e" title="Link to this definition">¶</a></dt>372<dd><p>display token names using the exact type</p>373</dd></dl>374 375<p>If <code class="file docutils literal notranslate"><span class="pre">filename.py</span></code> is specified its contents are tokenized to stdout.376Otherwise, tokenization is performed on stdin.</p>377</section>378<section id="examples">379<h2>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h2>380<p>Example of a script rewriter that transforms float literals into Decimal381objects:</p>382<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">tokenize</span><span class="w"> </span><span class="kn">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>383<span class="kn">from</span><span class="w"> </span><span class="nn">io</span><span class="w"> </span><span class="kn">import</span> <span class="n">BytesIO</span>384 385<span class="k">def</span><span class="w"> </span><span class="nf">decistmt</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>386<span class="w"> </span><span class="sd">"""Substitute Decimals for floats in a string of statements.</span>387 388<span class="sd"> >>> from decimal import Decimal</span>389<span class="sd"> >>> s = 'print(+21.3e-5*-.1234/81.7)'</span>390<span class="sd"> >>> decistmt(s)</span>391<span class="sd"> "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"</span>392 393<span class="sd"> The format of the exponent is inherited from the platform C library.</span>394<span class="sd"> Known cases are "e-007" (Windows) and "e-07" (not Windows). Since</span>395<span class="sd"> we're only showing 12 digits, and the 13th isn't close to 5, the</span>396<span class="sd"> rest of the output should be platform-independent.</span>397 398<span class="sd"> >>> exec(s) #doctest: +ELLIPSIS</span>399<span class="sd"> -3.21716034272e-0...7</span>400 401<span class="sd"> Output from calculations with Decimal should be identical across all</span>402<span class="sd"> platforms.</span>403 404<span class="sd"> >>> exec(decistmt(s))</span>405<span class="sd"> -3.217160342717258261933904529E-7</span>406<span class="sd"> """</span>407 <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>408 <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="s1">'utf-8'</span><span class="p">))</span><span class="o">.</span><span class="n">readline</span><span class="p">)</span> <span class="c1"># tokenize the string</span>409 <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>410 <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="s1">'.'</span> <span class="ow">in</span> <span class="n">tokval</span><span class="p">:</span> <span class="c1"># replace NUMBER tokens</span>411 <span class="n">result</span><span class="o">.</span><span class="n">extend</span><span class="p">([</span>412 <span class="p">(</span><span class="n">NAME</span><span class="p">,</span> <span class="s1">'Decimal'</span><span class="p">),</span>413 <span class="p">(</span><span class="n">OP</span><span class="p">,</span> <span class="s1">'('</span><span class="p">),</span>414 <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>415 <span class="p">(</span><span class="n">OP</span><span class="p">,</span> <span class="s1">')'</span><span class="p">)</span>416 <span class="p">])</span>417 <span class="k">else</span><span class="p">:</span>418 <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>419 <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="s1">'utf-8'</span><span class="p">)</span>420</pre></div>421</div>422<p>Example of tokenizing from the command line. The script:</p>423<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">say_hello</span><span class="p">():</span>424 <span class="nb">print</span><span class="p">(</span><span class="s2">"Hello, World!"</span><span class="p">)</span>425 426<span class="n">say_hello</span><span class="p">()</span>427</pre></div>428</div>429<p>will be tokenized to the following output where the first column is the range430of the line/column coordinates where the token is found, the second column is431the name of the token, and the final column is the value of the token (if any)</p>432<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-m<span class="w"> </span>tokenize<span class="w"> </span>hello.py433<span class="go">0,0-0,0: ENCODING 'utf-8'</span>434<span class="go">1,0-1,3: NAME 'def'</span>435<span class="go">1,4-1,13: NAME 'say_hello'</span>436<span class="go">1,13-1,14: OP '('</span>437<span class="go">1,14-1,15: OP ')'</span>438<span class="go">1,15-1,16: OP ':'</span>439<span class="go">1,16-1,17: NEWLINE '\n'</span>440<span class="go">2,0-2,4: INDENT ' '</span>441<span class="go">2,4-2,9: NAME 'print'</span>442<span class="go">2,9-2,10: OP '('</span>443<span class="go">2,10-2,25: STRING '"Hello, World!"'</span>444<span class="go">2,25-2,26: OP ')'</span>445<span class="go">2,26-2,27: NEWLINE '\n'</span>446<span class="go">3,0-3,1: NL '\n'</span>447<span class="go">4,0-4,0: DEDENT ''</span>448<span class="go">4,0-4,9: NAME 'say_hello'</span>449<span class="go">4,9-4,10: OP '('</span>450<span class="go">4,10-4,11: OP ')'</span>451<span class="go">4,11-4,12: NEWLINE '\n'</span>452<span class="go">5,0-5,0: ENDMARKER ''</span>453</pre></div>454</div>455<p>The exact token type names can be displayed using the <a class="reference internal" href="#cmdoption-tokenize-e"><code class="xref std std-option docutils literal notranslate"><span class="pre">-e</span></code></a> option:</p>456<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>-m<span class="w"> </span>tokenize<span class="w"> </span>-e<span class="w"> </span>hello.py457<span class="go">0,0-0,0: ENCODING 'utf-8'</span>458<span class="go">1,0-1,3: NAME 'def'</span>459<span class="go">1,4-1,13: NAME 'say_hello'</span>460<span class="go">1,13-1,14: LPAR '('</span>461<span class="go">1,14-1,15: RPAR ')'</span>462<span class="go">1,15-1,16: COLON ':'</span>463<span class="go">1,16-1,17: NEWLINE '\n'</span>464<span class="go">2,0-2,4: INDENT ' '</span>465<span class="go">2,4-2,9: NAME 'print'</span>466<span class="go">2,9-2,10: LPAR '('</span>467<span class="go">2,10-2,25: STRING '"Hello, World!"'</span>468<span class="go">2,25-2,26: RPAR ')'</span>469<span class="go">2,26-2,27: NEWLINE '\n'</span>470<span class="go">3,0-3,1: NL '\n'</span>471<span class="go">4,0-4,0: DEDENT ''</span>472<span class="go">4,0-4,9: NAME 'say_hello'</span>473<span class="go">4,9-4,10: LPAR '('</span>474<span class="go">4,10-4,11: RPAR ')'</span>475<span class="go">4,11-4,12: NEWLINE '\n'</span>476<span class="go">5,0-5,0: ENDMARKER ''</span>477</pre></div>478</div>479<p>Example of tokenizing a file programmatically, reading unicode480strings instead of bytes with <a class="reference internal" href="#tokenize.generate_tokens" title="tokenize.generate_tokens"><code class="xref py py-func docutils literal notranslate"><span class="pre">generate_tokens()</span></code></a>:</p>481<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">tokenize</span>482 483<span class="k">with</span> <span class="n">tokenize</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">'hello.py'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>484 <span class="n">tokens</span> <span class="o">=</span> <span class="n">tokenize</span><span class="o">.</span><span class="n">generate_tokens</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">)</span>485 <span class="k">for</span> <span class="n">token</span> <span class="ow">in</span> <span class="n">tokens</span><span class="p">:</span>486 <span class="nb">print</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>487</pre></div>488</div>489<p>Or reading bytes directly with <a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code></a>:</p>490<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">tokenize</span>491 492<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'hello.py'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>493 <span class="n">tokens</span> <span class="o">=</span> <span class="n">tokenize</span><span class="o">.</span><span class="n">tokenize</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">)</span>494 <span class="k">for</span> <span class="n">token</span> <span class="ow">in</span> <span class="n">tokens</span><span class="p">:</span>495 <span class="nb">print</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>496</pre></div>497</div>498</section>499</section>500 501 502 <div class="clearer"></div>503 </div>504 </div>505 </div>506 <div class="sphinxsidebar" role="navigation" aria-label="Main">507 <div class="sphinxsidebarwrapper">508 <div>509 <h3><a href="../contents.html">Table of Contents</a></h3>510 <ul>511<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source</a><ul>512<li><a class="reference internal" href="#tokenizing-input">Tokenizing Input</a></li>513<li><a class="reference internal" href="#command-line-usage">Command-Line Usage</a></li>514<li><a class="reference internal" href="#examples">Examples</a></li>515</ul>516</li>517</ul>518 519 </div>520 <div>521 <h4>Previous topic</h4>522 <p class="topless"><a href="keyword.html"523 title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">keyword</span></code> — Testing for Python keywords</a></p>524 </div>525 <div>526 <h4>Next topic</h4>527 <p class="topless"><a href="tabnanny.html"528 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tabnanny</span></code> — Detection of ambiguous indentation</a></p>529 </div>530 <script>531 document.addEventListener('DOMContentLoaded', () => {532 const title = document.querySelector('meta[property="og:title"]').content;533 const elements = document.querySelectorAll('.improvepage');534 const pageurl = window.location.href.split('?')[0];535 elements.forEach(element => {536 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));537 url.searchParams.set('pagetitle', title);538 url.searchParams.set('pageurl', pageurl);539 url.searchParams.set('pagesource', "library/tokenize.rst");540 element.href = url.toString();541 });542 });543 </script>544 <div role="note" aria-label="source link">545 <h3>This page</h3>546 <ul class="this-page-menu">547 <li><a href="../bugs.html">Report a bug</a></li>548 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>549 <li>550 <a href="https://github.com/python/cpython/blob/main/Doc/library/tokenize.rst?plain=1"551 rel="nofollow">Show source552 </a>553 </li>554 555 </ul>556 </div>557 </div>558<div id="sidebarbutton" title="Collapse sidebar">559<span>«</span>560</div>561 562 </div>563 <div class="clearer"></div>564 </div> 565 <div class="related" role="navigation" aria-label="Related">566 <h3>Navigation</h3>567 <ul>568 <li class="right" style="margin-right: 10px">569 <a href="../genindex.html" title="General Index"570 >index</a></li>571 <li class="right" >572 <a href="../py-modindex.html" title="Python Module Index"573 >modules</a> |</li>574 <li class="right" >575 <a href="tabnanny.html" title="tabnanny — Detection of ambiguous indentation"576 >next</a> |</li>577 <li class="right" >578 <a href="keyword.html" title="keyword — Testing for Python keywords"579 >previous</a> |</li>580 581 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>582 <li><a href="https://www.python.org/">Python</a> »</li>583 <li class="switchers">584 <div class="language_switcher_placeholder"></div>585 <div class="version_switcher_placeholder"></div>586 </li>587 <li>588 589 </li>590 <li id="cpython-language-and-version">591 <a href="../index.html">3.15.0a6 Documentation</a> »592 </li>593 594 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>595 <li class="nav-item nav-item-2"><a href="language.html" >Python Language Services</a> »</li>596 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source</a></li>597 <li class="right">598 599 600 <div class="inline-search" role="search">601 <form class="inline-search" action="../search.html" method="get">602 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">603 <input type="submit" value="Go">604 </form>605 </div>606 |607 </li>608 <li class="right">609<label class="theme-selector-label">610 Theme611 <select class="theme-selector" oninput="activateTheme(this.value)">612 <option value="auto" selected>Auto</option>613 <option value="light">Light</option>614 <option value="dark">Dark</option>615 </select>616</label> |</li>617 618 </ul>619 </div> 620 <div class="footer">621 © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.622 <br>623 This page is licensed under the Python Software Foundation License Version 2.624 <br>625 Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.626 <br>627 628 See <a href="/license.html">History and License</a> for more information.<br>629 630 631 <br>632 633 The Python Software Foundation is a non-profit corporation.634<a href="https://www.python.org/psf/donations/">Please donate.</a>635<br>636 <br>637 Last updated on Mar 10, 2026 (08:58 UTC).638 639 <a href="/bugs.html">Found a bug</a>?640 641 <br>642 643 Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.644 </div>645 646 </body>647</html>