tokenize Finds Comments Outside Strings

tokenize.generate_tokens applies lexical rules, so COMMENT tokens never include # characters that live inside string literals.

PythonData Integrity

Code

pythonsnippet
17 lines
import io
import tokenize

source = '''route = "/reports/<id>"  # endpoint for the export
greeting = "hi # there"  # the # inside quotes stays text
# TODO: paginate the export
total = len(route)  # trailing note
'''

comments = []
for token in tokenize.generate_tokens(io.StringIO(source).readline):
    if token.type == tokenize.COMMENT:
        comments.append(token.string)

print(f"{len(comments)} comments outside strings")
for comment in comments:
    print(" ", comment)

The path from source to result

Repetition is confined to for token in tokenize.generate_tokens(io.StringIO(source).readline) — the rest of the file is straight-line.

Demo state sits in top-level bindings: source, greeting, total, comments.

What to watch for

  • Requires tokenize as a package; the snippet will not run without it.

Key statements

for token in tokenize.generate_tokens(io.StringIO(source).readline):
    if token.type == tokenize.COMMENT:
        comments.append(token.string)
for comment in comments:
    print(" ", comment)

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `tokenize`. Without it the snippet will not load.