On this page
tokenize
Prev: token | Up: stdlib_module | Next: tomllib
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — tokenize
Tags: #public #python3 #stdlib
Import
import tokenize
Overview
Exact lexical tokenizer for Python source code (generate_tokens, tokenize, untokenize, detect_encoding) that preserves comments, whitespace, indentation (INDENT/DEDENT), and exact (line, col) coordinates—information discarded by ast. Essential for code formatters, comment extractors, syntax highlighters, and custom Python preprocessors.
Quick Start
import io
import tokenize
code = "x = 42 # answer\n"
tokens = list(tokenize.generate_tokens(io.StringIO(code).readline))
comments = [tok.string for tok in tokens if tok.type == tokenize.COMMENT]
assert comments == ["# answer"]
Implementation Walkthrough
1. Extracting Identifiers & Comments While Preserving Positions
tokenize.open(path) inspects # -*- coding: ... -*- headers automatically (defaulting to UTF-8) before opening a source file as text:
import io
import tokenize
def extract_names_and_comments(source: str) -> tuple[list[str], list[str]]:
names, comments = [], []
for tok in tokenize.generate_tokens(io.StringIO(source).readline):
if tok.type == tokenize.NAME:
names.append(tok.string)
elif tok.type == tokenize.COMMENT:
comments.append(tok.string)
return names, comments
names, comments = extract_names_and_comments("def f(): # hi\n return 1\n")
assert "f" in names and comments == ["# hi"]
Gotchas & Boundaries
tokenize.tokenize()takes a bytesreadlinecallable, whereastokenize.generate_tokens()takes a strreadlinecallable.- Invalid syntax (like unclosed strings or bad indentation) raises
tokenize.TokenErrororIndentationError: Handle both when scanning arbitrary user files. - Use ast when you need semantic syntax structure (expressions, calls, classes) rather than raw lexical tokens.
Common Functions
- tokenize.detect_encoding() —
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. - tokenize.generate_tokens() —
generate_tokens(readline)— Tokenize a source reading Python code as unicode strings. - tokenize.open() —
open(filename)— Open a file in read only mode using the encoding detected by detect_encoding(). - tokenize.tokenize() —
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 - tokenize.untokenize() —
untokenize(iterable)— Transform tokens back into Python source code.
Classes & Objects
- tokenize.TokenError —
tokenize.TokenErrorclass. (Methods:.add_note(),.with_traceback()) - tokenize.TokenInfo —
tokenize.TokenInfoclass. (Methods:.count(),.exact_type(),.index())
Constants & Attributes
tokenize.AMPER(int) =19tokenize.AMPEREQUAL(int) =41tokenize.AT(int) =49tokenize.ATEQUAL(int) =50tokenize.CIRCUMFLEX(int) =32tokenize.CIRCUMFLEXEQUAL(int) =43tokenize.COLON(int) =11tokenize.COLONEQUAL(int) =53tokenize.COMMA(int) =12tokenize.COMMENT(int) =65tokenize.DEDENT(int) =6tokenize.DOT(int) =23tokenize.DOUBLESLASH(int) =47tokenize.DOUBLESLASHEQUAL(int) =48tokenize.DOUBLESTAR(int) =35
Linked from
Related notes
- tuts/python3/stdlib_module/ast Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/token Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tomllib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/sys Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/sysconfig Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/tokenize/detect_encoding Linked here; shared tags: #stdlib