This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author pgacv2
Recipients pgacv2
Date 2017-05-01.16:19:50
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1493655591.13.0.717623445702.issue30220@psf.upfronthosting.co.za>
In-reply-to
Content
ArgumentParser._get_value() has two exception handlers: one for ArgumentTypeError, and one for (TypeError, ValueError). But in the latter case, any custom message I include the TypeError or ValueError is ignored and replaced with a generic "invalid value" message.

I don't see why the module wouldn't first check for a custom message in a TypeError or ValueError exception, as it does for ArgumentTypeError, and only use the generic message if a custom one is not specified. The current behavior does not let you to give the user a detailed reason for the exception unless you raise ArgumentTypeError, which is considered an implementation detail as mentioned in #20039, and also doesn't feel right for errors that are not related to the argument's type.


Code to reproduce:

import argparse

def nonnegative_not_suppressed(arg):
  try:
    x = int(arg)
    if x >= 0:
      return x
    else:
      raise argparse.ArgumentTypeError('Enter a nonnegative integer')
  except:
    raise argparse.ArgumentTypeError('Enter a nonnegative integer')

def nonnegative_suppressed(arg):
  try:
    x = int(arg)
    if x >= 0:
      return x
    else:
      raise ValueError('Enter a nonnegative integer')
  except:
    raise ValueError('Enter a nonnegative integer')

p = argparse.ArgumentParser('parser')
p.add_argument('--no-suppress', type=nonnegative_not_suppressed)
p.add_argument('--suppress', type=nonnegative_suppressed)
p.parse_args(['--no-suppress', '-4']) # Displays "Enter a nonnegative integer"
p.parse_args(['--suppress', '-4']) # Displays "invalid nonnegative_suppressed value: '-4'"
History
Date User Action Args
2017-05-01 16:19:51pgacv2setrecipients: + pgacv2
2017-05-01 16:19:51pgacv2setmessageid: <1493655591.13.0.717623445702.issue30220@psf.upfronthosting.co.za>
2017-05-01 16:19:51pgacv2linkissue30220 messages
2017-05-01 16:19:50pgacv2create