Skip to content

Support for Automatically Parsing Negative Number Arguments #2676

@thomask77

Description

@thomask77

I would like to re-open the discussion from issue #555 and #1624.

My program makes heavy use of numeric arguments, including negative numbers, special float values (NaN, Infinity..), negative hex numbers, etc.

At the moment I'm using the following monkey patch as a work-around:

from click.parser import OptionParser, ParsingState


def _is_number(arg: str) -> bool:
    try:
        _ = int(arg, 0)
    except ValueError:
        try:
            _ = float(arg)
        except ValueError:
            return False
    return True


# Allow negative numbers as arguments
#
# Based on click/parser.py v8.1.7
#
def _process_args_for_options(self, state: ParsingState) -> None:
    while state.rargs:
        arg = state.rargs.pop(0)
        if arg == "--":
            return
        elif arg[:1] in self._opt_prefixes and len(arg) > 1 and not _is_number(arg):
            self._process_opts(arg, state)
        elif self.allow_interspersed_args:
            state.largs.append(arg)
        else:
            state.rargs.insert(0, arg)
            return


# Monkey-patch the OptionParser class
#
OptionParser._process_args_for_options = _process_args_for_options

It would be nice, if click would offer an official mode that accepts negative numbers.
I can also submit a PR, but would need further input on how to properly integrate the feature.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions