On this page
  1. token
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Checking Exact Operator Tokens (exact_type)
  7. Gotchas & Boundaries
  8. Constants & Attributes

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 & Attributes

Linked from

Related notes