On this page
token
Prev: tkinter | Up: stdlib_module | Next: tokenize
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — token
Tags: #public #python3 #stdlib
Import
import token
Overview
Numeric constants and helper mappings (tok_name, EXACT_TOKEN_TYPES, ISEOF(), ISNONTERMINAL()) for every lexical token type produced by Python's tokenize scanner. Use token to match token types cleanly without hardcoding magic integers when writing formatters, linters, or code transformers.
Quick Start
import io
import token
import tokenize
tokens = list(tokenize.generate_tokens(io.StringIO("x = 42").readline))
names = [(token.tok_name[t.type], t.string) for t in tokens if t.type not in (token.NEWLINE, token.ENDMARKER)]
assert names == [("NAME", "x"), ("OP", "="), ("NUMBER", "42")]
Implementation Walkthrough
1. Checking Exact Operator Tokens (exact_type)
tokenize emits token.OP as t.type for operators/delimiters, while t.exact_type gives the specific token constant (like token.EQUAL or token.LPAR):
import io
import token
import tokenize
toks = list(tokenize.generate_tokens(io.StringIO("a == b").readline))
ops = [t.exact_type for t in toks if t.type == token.OP]
assert ops == [token.EQEQUAL]
assert token.EXACT_TOKEN_TYPES["=="] == token.EQEQUAL
Gotchas & Boundaries
- Constants can shift across Python versions: Never hardcode integer token IDs; always reference
token.NAME,token.OP,token.FSTRING_START, etc. - Use
tokenize.generate_tokensfor actual lexing: Thetokenmodule only holds constants and predicates; tokenize does the scanning.
Constants & Attributes
token.AMPER(int) =19token.AMPEREQUAL(int) =41token.AT(int) =49token.ATEQUAL(int) =50token.CIRCUMFLEX(int) =32token.CIRCUMFLEXEQUAL(int) =43token.COLON(int) =11token.COLONEQUAL(int) =53token.COMMA(int) =12token.COMMENT(int) =65token.DEDENT(int) =6token.DOT(int) =23token.DOUBLESLASH(int) =47token.DOUBLESLASHEQUAL(int) =48token.DOUBLESTAR(int) =35
Linked from
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tkinter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tokenize 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/warnings Linked here; shared tags: #stdlib
- tuts/c/stdlib shared tags: #stdlib