argparse icon indicating copy to clipboard operation
argparse copied to clipboard

argparse does not accept negative values

Open hpaulj opened this issue 14 years ago • 1 comments

argparse .js does not accept negative values, either as positional arguments or arguments for options

The problem, apparently, is that Python not [] and not [True] is different from JS ![] and ![true]. The original Python is:

class _ActionsContainer(object):

    def __init__(...
        # whether or not there are any optionals that look like negative
        # numbers -- uses a list so it can be shared and edited
        self._has_negative_number_optionals = []
        ...
    def _add_action(self, action):
        ...
        # set the flag if any option strings look like negative numbers
        for option_string in action.option_strings:
            if self._negative_number_matcher.match(option_string):
                if not self._has_negative_number_optionals:
                    self._has_negative_number_optionals.append(True)

So self._has_negative_number_optionals is either [] or [True], and not [] == True, not[True]==False

later during parsing it is used:

class ArgumentParser(_AttributeHolder, _ActionsContainer):
...
    def _parse_optional(self, arg_string):
    ...
        if self._negative_number_matcher.match(arg_string):
            if not self._has_negative_number_optionals:
                return None

in javascript ![true] and ![] both are false

!_.any(self._has_negative_number_optionals) will behave as in Python.

one possible correction then is to test it as in

    if (optionString.match(self._regexpNegativeNumber)) {
      if (!_.any(self._hasNegativeNumberOptionals)) {
        self._hasNegativeNumberOptionals.push(true);
      }
    }

also in ArgumentParser.prototype._parseOptional = function (argString)

It is tempting to try to simplify things by replacing the [],[true] with false, true. But as shown in the initialization of ArgumentGroup objects, this attribute is shared among 3 groups, the parser itself, and its _optionals and _positionals. Modifying the list value preserves this sharing, while assigning a new value would break it.

hpaulj avatar Nov 29 '12 23:11 hpaulj

thanks

shkuropat avatar Dec 02 '12 18:12 shkuropat