pydoc > tokenize

📖 Name

tokenize — Tokenization help for Python programs.

🚀 Quick Reference

Use CaseCommandDescription
🔍 Tokenize a Python filetokenize(open('file.py', 'rb').readline)Generate 5-tuples of tokens from a file opened in binary mode
🔍 Tokenize a stringtokenize(io.BytesIO(code.encode()).readline)Tokenize Python source code from a string
🔤 Tokenize unicode stringgenerate_tokens(readline)Same as tokenize() but expects str objects instead of bytes
🔄 Untokenize back to sourceuntokenize(iterable)Transform tokens back into Python source code (bytes)
🌐 Detect file encodingdetect_encoding(readline)Detect encoding from BOM or PEP-263 cookie (returns (encoding, lines))
📦 Access token type constantstokenize.NAME, tokenize.NUMBER, etc.Integer constants for token types (e.g., NAME = 1, NUMBER = 2)
📋 Look up token nametokenize.tok_name[type]Map from integer token type to string name (e.g., 1 → 'NAME')

📚 Module Reference

https://docs.python.org/3.10/library/tokenize.html

The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above.

📝 Description

tokenize(readline) is a generator that breaks a stream of bytes into Python tokens. It decodes the bytes according to PEP-0263 for determining source file encoding.

It accepts a readline-like method which is called repeatedly to get the next line of input (or b"" for EOF). It generates 5-tuples with these members:

It is designed to match the working of the Python tokenizer exactly, except that it produces COMMENT tokens for comments and gives type OP for all operators. Additionally, all token lists start with an ENCODING token which tells you which encoding was used to decode the bytes stream.

📦 Classes

TokenInfo (inherits from builtins.tuple)

🔷 TokenInfo

TokenInfo(type, string, start, end, line)

Method resolution order: TokenInfobuiltins.tuplebuiltins.object

Methods defined here:

Readonly properties defined here:

Data descriptors defined here:

Methods inherited from TokenInfo (generated by namedtuple):

Class methods inherited from TokenInfo:

Static methods inherited from TokenInfo:

Data descriptors inherited from TokenInfo (field aliases):

__match_args__ = ('type', 'string', 'start', 'end', 'line')
_field_defaults = {}
_fields = ('type', 'string', 'start', 'end', 'line')

Methods inherited from builtins.tuple:

Class methods inherited from builtins.tuple:

🔧 Functions

🔍 detect_encoding(readline)

The detect_encoding() 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 tokenize() generator.

It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in.

It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in PEP-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned.

If no encoding is specified, then the default of 'utf-8' will be returned.

🔤 generate_tokens(readline)

Tokenize a source reading Python code as unicode strings.

This has the same API as tokenize(), except that it expects the readline callable to return str objects instead of bytes.

⚙️ tokenize(readline)

The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as bytes. Alternatively, readline can be a callable function terminating with StopIteration:

readline = open(myfile, 'rb').__next__  # Example of alternate readline

The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) 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 is the physical line.

The first token sequence will always be an ENCODING token which tells you which encoding was used to decode the bytes stream.

🔄 untokenize(iterable)

Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize.

Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor.

Round-trip invariant for full input: Untokenized source will match input source exactly

Round-trip invariant for limited input:

# Output bytes will tokenize back to the input
t1 = [tok[:2] for tok in tokenize(f.readline)]
newcode = untokenize(t1)
readline = BytesIO(newcode).readline
t2 = [tok[:2] for tok in tokenize(readline)]
assert t1 == t2

📊 Data

Token type constants (integers):

__all__ = ['tok_name', 'ISTERMINAL', 'ISNONTERMINAL', 'ISEOF', 'ENDMARKER', ...]

tok_name = {0: 'ENDMARKER', 1: 'NAME', 2: 'NUMBER', 3: 'STRING', 4: 'NEWLINE', ...}

👤 Author

Ka-Ping Yee <ping@lfw.org>

🏆 Credits

GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger, Trent Nelson, Michael Foord

📁 File

/usr/lib/python3.10/tokenize.py

tokenize
📖 Name 🚀 Quick Reference 📚 Module Reference 📝 Description 📦 Classes
🔷 TokenInfo
🔧 Functions
🔍 detect_encoding(readline) 🔤 generate_tokens(readline) ⚙️ tokenize(readline) 🔄 untokenize(iterable)
📊 Data 👤 Author 🏆 Credits 📁 File

Generated by phpman v4.10.0-7-g98e9fd5 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-09-02 22:08 @216.73.216.239
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!

^_top_^