Skip to content

Latest commit

 

History

History
45 lines (36 loc) · 1.29 KB

20220921175618.md

File metadata and controls

45 lines (36 loc) · 1.29 KB

Get close matches

In Python you can use get_close_matches() from the difflib module to return a list of the best “good enough” matches:

>>> from difflib import get_close_matches
>>> names = ['julian', 'pybites', 'bob', 'tim', 'python', 'sara', 'james', 'ana']
>>> get_close_matches('pythonista', names)
['python']
>>> get_close_matches('pybit', names)
['pybites']
>>> get_close_matches('jul', names)
['julian']
>>> get_close_matches('ara', names)
['sara', 'ana']

Django leverages this Python feature in its http://manage.py command to enhance user experience. 🐍

When you mistype a command, it suggests the closest match:

# core/management/__init__.py

    def fetch_command(self, subcommand):
        commands = get_commands()
        try:
            app_name = commands[subcommand]
        except KeyError:
            ...
            possible_matches = get_close_matches(subcommand, commands)
            sys.stderr.write('Unknown command: %r' % subcommand)
            if possible_matches:
                sys.stderr.write('. Did you mean %s?' % possible_matches[0])
            sys.stderr.write("\nType '%s help' for usage.\n" % self.prog_name)
            sys.exit(1)

For example: $ python http://manage.py migr Unknown command: 'migr'. Did you mean migrate?

📈😍

#difflib #django