difflib Suggests Close Matches For Typos
get_close_matches ranks known strings by similarity with a cutoff floor, turning mistyped CLI commands into a did-you-mean suggestion list.
Code
import difflib
# A CLI offers these subcommands; typos map back to the nearest real one.
COMMANDS = ["deploy", "rollback", "status", "logs", "config", "destroy"]
def suggest(typed: str, cutoff: float = 0.6) -> list[str]:
# n caps the result count; cutoff is the required similarity floor.
return difflib.get_close_matches(typed, COMMANDS, n=2, cutoff=cutoff)
for typed in ["deplo", "statu", "rollbck", "logs-all", "zzz"]:
print(f"{typed!r} -> {suggest(typed) or 'no suggestion'}")
# cutoff sets how similar a candidate must be: 'st' clears 0.4 but not 0.6.
print("st @ 0.4:", difflib.get_close_matches("st", COMMANDS, n=1, cutoff=0.4))
print("st @ 0.6:", difflib.get_close_matches("st", COMMANDS, n=1, cutoff=0.6))How the snippet works
Structurally, expect the function suggest and nothing else.
for typed in ["deplo", "statu", "rollbck", "logs-all", "zzz"] is the loop that carries the per-item work.
Points of care
- Nothing to install: the snippet stays inside the standard library.
Applying it
Signature: def suggest(typed: str, cutoff: float = 0.6) -> list[str]
The file announces its steps in the output: st @ 0.4:, st @ 0.6:.
Import suggest from the file and call it — the rest of the code is implementation detail.
Statements that matter
def suggest(typed: str, cutoff: float = 0.6) -> list[str]:
# n caps the result count; cutoff is the required similarity floor.
return difflib.get_close_matches(typed, COMMANDS, n=2, cutoff=cutoff)
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Every import resolves inside the standard library — `difflib`. The file defines `suggest` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.