On this page
  1. tokenize
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Extracting Identifiers & Comments While Preserving Positions
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes