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.

PythonCli Tooling

Code

pythonsnippet
15 lines
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

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.