← All notes

Python tokenize: a lexical scanner for source code

Answer: The tokenize module provides a lexical scanner for Python source code, written in Python. That scanner returns comments as tokens as well. detect_encoding will call readline a maximum of twice.

A lexical scanner for source

The tokenize module provides a lexical scanner for Python source code, written in Python.

Comments are returned as tokens as well, which is useful for pretty-printers.

Operator and delimiter tokens, and also Ellipsis, come back as the generic OP token type.

The exact_type property on TokenInfo gives the exact token type.

Encoding detection and valid input

detect_encoding detects the encoding for decoding a Python source file.

The function will call readline a maximum of twice, then return the encoding used.

Functions in this module are only designed to parse syntactically valid Python code.

When providing invalid Python code, the behavior is undefined and it can change at any point.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python Software Foundation, tokenize — Tokenizer for Python source; CPython, tokenize documentation (source). PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python Software Foundation, tokenize — Tokenizer for Python source; CPython, tokenize documentation (source). PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.

Cite this

Permanent ID: iil:note:980y8twa

iinventedlight. 2026. "Python tokenize: a lexical scanner for source code." iinventedlight Library, iil:note:980y8twa, version of 2026-11-23. https://iinventedlight.com/library/notes/python-tokenize/. License: CC-BY-4.0.

@misc{iil_note_980y8twa,
  author = {{iinventedlight}},
  title = {{Python tokenize: a lexical scanner for source code}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-23},
  url = {https://iinventedlight.com/library/notes/python-tokenize/},
  note = {Permanent ID iil:note:980y8twa. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-tokenize.md.