Python argparser prefix matching

Dawid Laszuk published on
2 min, 216 words

Python has a built in argument parser called argparse. It's the first library most folks use when writing a quick CLI tool. However, it's often quickly abandoned once the app grows in complexity. Unfrotunately, too quickly.

I'm also guilty of too quickly switching to click (nice package) or fire (least favourite evil). I think that's because I have outdated view of what argparse can and cannot do. Just the other day, through accidental laziness I've learned that by default argparse does prefix matching. A flag can be shortened to the shortest unique prefix. For example, if a program has a flag --verbose it can be called with --verb or --verbo or --verbose. This is a very useful feature that I've been missing out on.

Here's a quick example:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--very-big-number', type=float)
parser.add_argument('--verbose', action='store_true')
args = parser.parse_args()

args = parser.parse_args('--very 4242.42 --verb'.split())
# Namespace(very_big_number=4242.42, verbose=True)

And if there's an overlap in prefixes then argparse will raise an error:

args = parser.parse_args('--ver'.split())

# usage: [-h] [--very-big-number VERY_BIG_NUMBER] [--verbose]
# error: ambiguous option: --ver could match --verbose, --very-big-number