Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable abbreviation in argparse

argparse uses per default abbreviation in unambiguous cases.

I don't want abbreviation and I'd like to disable it. But didn't find it in the documentation.

Is it possible?

Example:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--send', action='store_true')
parser.parse_args(['--se']) # returns Namespace(send=True)

But I want it only to be true when the full parameter is supplied. To prevent user errors.

UPDATE:

I created a ticket at python bugtracker after Vikas answer. And it already has been processed.

like image 859
juwens Avatar asked May 25 '12 08:05

juwens


2 Answers

As of Python 3.5.0 you can disable abbreviations by initiating the ArgumentParser with the following:

parser = argparse.ArgumentParser(allow_abbrev=False)

Also see the documentation.

like image 93
anthonyryan1 Avatar answered Sep 27 '22 17:09

anthonyryan1


No, apparently this is not possible. At least in Python 2.7.2.

First, I took a look into the documentation - to no avail.

Then I opened the Lib\argparse.py and looked through the source code. Omitting a lot of details, it seems that each argument is parsed by a regular expression like this (argparse:2152):

    # allow one or more arguments
    elif nargs == ONE_OR_MORE:
        nargs_pattern = '(-*A[A-]*)'

This regex will successfully parse both '-' and '--', so we have no control over the short and long arguments. Other regexes use the -* construct too, so it does not depend on the type of the parameter (no sub-arguments, 1 sub-argument etc).

Later in the code double dashes are converted to one dash (only for non-optional args), again, without any flags to control by user:

    # if this is an optional action, -- is not allowed
    if action.option_strings:
        nargs_pattern = nargs_pattern.replace('-*', '')
        nargs_pattern = nargs_pattern.replace('-', '')
like image 28
Vladimir Sinenko Avatar answered Sep 27 '22 17:09

Vladimir Sinenko