◐ Shell
clean mode source ↗

Message 230018 - Python tracker

Patch tests are added to an existing 'Lib/test/test_argparse.py' file.  I use existing test cases as a pattern any new tests.

---------------------

Your test file runs fine with the patch I proposed for Issue 9334.

---------------------

The argparse code uses '_negative_number_matcher' for 2 purposes

1) to test whether an option_string looks like a negative number, and set the 'self._has_negative_number_optionals' attribute.

    parser.add_argument('-2')
    parser.add_argument('-1.234')

2) to test whether an argument string (an element of sys.argv) looks like one of those option_strings, or is an argument (positional or argument to your '-a').

The 'type' in for your '-a' argument is separate issue.  That is used convert a string to a number, float, complex or what ever, and raise an error it if can't do so.

In your case './test.py -a -1e5' fails because '-1e5' fails the 2nd test, and thus is not recognized as an argument to '-a'. Understanding the details of this requires digging into the logic of the _parse_optional() method.

'./test.py -a-1e5' or './test.py -a=-1e5' work because the number is correctly recognized as an argument.

For issue 9334 I looked at generalizing '_negative_number_matcher' as you did.  But unless you want to use something like:

    parser.add_argument('-1.2e-34')

and set the 'self._has_negative_number_optionals' to '[True]', the matcher doesn't need to be more general.

It's only the test in '_parse_optional()' that needs to be generalized to handle scientific and complex notation.  And for that I figured that wrapping 'complex()' in a 'try' block was just as general and reliable as a complicated 're' pattern.  At least that was my claim in issue 9334, and I haven't gotten feedback on that.

I'd suggest reading the 9334 discussion, and testing that patch.  That patch includes some tests for scientific and complex numbers.

That issue and patch also adds a 'args_default_to_positional' parameter. I wonder if the two changes should be put in separate patches.