brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's difflib.get_close_matches adds a did you mean to your script

Python
~/tips/tip-python-difflib-get-close-matches

msg += f", did you mean {hint[0]!r}?"

Suggest the closest valid option when someone mistypes a command or name.

When a small command line tool gets an unknown subcommand, I like it to suggest the right one, the way git does. difflib has that built in.

import sys
from difflib import get_close_matches

commands = ["start", "stop", "restart", "status"]
cmd = sys.argv[1]
if cmd not in commands:
    hint = get_close_matches(cmd, commands, n=1)
    msg = f"unknown command {cmd!r}"
    if hint:
        msg += f", did you mean {hint[0]!r}?"
    sys.exit(msg)

Running it with strat prints did you mean 'start'?. The function scores every option by similarity and returns the best ones, best first. n limits how many you get, and cutoff (default 0.6) decides how similar something has to be to count at all.

It works on config keys too. When a YAML file has retentoin, a hint pointing at retention saves someone a few minutes of staring.

The scoring compares characters and doesn’t know anything about meaning or keyboard layout, so short words give odd suggestions. With only two or three letters, a lot of things score similar. Raise cutoff to around 0.75 if your list has many short names, and an empty result is fine: then you just print the error without a hint.

Further reading: difflib.get_close_matches

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link